164
ADVANCE COMPUTER SCIENCE Topic Objective: At the end of this topic the student will be able to understand: History of Computer Programming Java Definition/Overview: Overview: A personal computer (PC) is any general-purpose computer whose original sales price, size, and capabilities make it useful for individuals, and which is intended to be operated directly by an end user, with no intervening computer operator. Today a PC may be a desktop computer, a laptop computer or a tablet computer. The most common operating systems are Microsoft Windows, Mac OS X and Linux, while the most common microprocessors are x86-compatible CPUs, ARM architecture CPUs and PowerPC CPUs. Software applications for personal computers include word processing, spreadsheets, databases, games, and myriad of personal productivity and special-purpose software. Modern personal computers often have high-speed or dial-up connections to the Internet, allowing access to the World Wide Web and a wide range of other resources. Key Points: 1. History The capabilities of the PC have changed greatly since the introduction of electronic computers. By the early 1970s, people in academic or research institutions had the opportunity for single-person use of a computer system in interactive mode for extended durations, although these systems would still have been too expensive to be owned by a single person. The introduction of the microprocessor, a single chip with all the circuitry that formerly occupied large cabinets, led to the proliferation of personal computers after about 1975. Early personal computers - generally called microcomputers - were sold often in Electronic kit form and in limited volumes, and were of interest mostly to hobbyists and www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in 1 www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in WWW.BSSVE.IN

figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

ADVANCE COMPUTER SCIENCE

Topic Objective:

At the end of this topic the student will be able to understand:

History of Computer

Programming

Java

Definition/Overview:

Overview: A personal computer (PC) is any general-purpose computer whose original sales

price, size, and capabilities make it useful for individuals, and which is intended to be

operated directly by an end user, with no intervening computer operator. Today a PC may be

a desktop computer, a laptop computer or a tablet computer. The most common operating

systems are Microsoft Windows, Mac OS X and Linux, while the most common

microprocessors are x86-compatible CPUs, ARM architecture CPUs and PowerPC CPUs.

Software applications for personal computers include word processing, spreadsheets,

databases, games, and myriad of personal productivity and special-purpose software. Modern

personal computers often have high-speed or dial-up connections to the Internet, allowing

access to the World Wide Web and a wide range of other resources.

Key Points:

1. History

The capabilities of the PC have changed greatly since the introduction of electronic

computers. By the early 1970s, people in academic or research institutions had the

opportunity for single-person use of a computer system in interactive mode for extended

durations, although these systems would still have been too expensive to be owned by a

single person. The introduction of the microprocessor, a single chip with all the circuitry that

formerly occupied large cabinets, led to the proliferation of personal computers after about

1975. Early personal computers - generally called microcomputers - were sold often in

Electronic kit form and in limited volumes, and were of interest mostly to hobbyists and

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

1www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 2: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

technicians. Minimal programming was done by toggle switches, and output was provided by

front panel indicators. Practical use required peripherals such as keyboards, computer

terminals, disk drives, and printers. By 1977, mass-market pre-assembled computers allowed

a wider range of people to use computers, focusing more on software applications and less on

development of the processor hardware.

Throughout the late 1970s and into the 1980s, computers were developed for household use,

offering personal productivity, programming and games. Somewhat larger and more

expensive systems (although still low-cost compared with minicomputers and mainframes)

were aimed for office and small business use. Workstations are characterized by high-

performance processors and graphics displays, with large local disk storage, networking

capability, and running under a multitasking operating system. Workstations are still used for

tasks such as computer-aided design, drafting and modelling, computation-intensive scientific

and engineering calculations, image processing, architectural modelling, and computer

graphics for animation and motion picture visual effects.

Eventually the market segments lost any technical distinction; business computers acquired

color graphics capability and sound, and home computers and game systems users used the

same processors and operating systems as office workers. Mass-market computers had

graphics capabilities and memory comparable to dedicated workstations of a few years

before. Even local area networking, originally a way to allow business computers to share

expensive mass storage and peripherals, became a standard feature of the personal computers

used at home.

Apple Macintosh of 1984 was the first device to become personal computer by a complete

list of contemporary criteria, which include Graphical User Interface, mouse, keyboard,

assembled body with size which allowed putting computer on a desktop, and price

comparable to average monthly income of a citizen. All of earlier attempts did not meet either

one or few of those conditions.

1.1 Market and sales

In 2001 125 million personal computers were shipped in comparison to 48 thousand

in 1977. More than 500 million PCs were in use in 2002, and one billion personal

computers had been sold worldwide since mid-1970s until this time. Of the latter

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

2www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 3: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

figure, 75 percent were professional or work related, while the rest sold for personal

or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

percent laptops and 2.1 percent servers. United States had received 38.8 percent (394

million) of the computers shipped, Europe 25 percent and 11.7 percent had gone to

Asia-Pacific region, the fastest-growing market as of 2002. The second billion was

expected to be sold by 2008. Almost half of all households in Western Europe had a

personal computer, and a computer could be found in 40 percent of homes in United

Kingdom, compared with only 13 percent in 1985.

The global PC shipments was 264 million units in year 2007, according to iSuppli , up

11.2 per cent from 239 million in 2006. . In year 2004, the global shipments was 183

million units, 11.6 percent increase over 2003. In 2003, 152.6 million PCs were

shipped, at an estimated value of $175 billion. In 2002, 136.7 million PCs were

shipped, at an estimated value of $175 billion. In 2000, 140.2 million PCs were

shipped, at an estimated value of $226 billion. Worldwide shipments of PCs surpassed

the 100-million mark in 1999, growing to 113.5 million units from 93.3 million units

in 1998. . In 1999, Asiahad 14,1 million units shipped.

As of June 2008, the number of personal computers in use worldwide hit one billion,

while another billion is expected to be reached by 2014. Mature markets like the

United States, Western Europe and Japan accounted for 58 percent of the worldwide

installed PCs. The emerging markets were expected to double their installed PCs by

2013 and to take 70 percent of the second billion PCs. About 180 million PCs (16

percent of the existing installed base) were expected to be replaced and 35 million to

be dumped into landfill in 2008. The whole installed base grew 12 percent annually.

In the developed world, there has been a vendor tradition to keep adding functions to

maintain high prices of personal computers. However, since the introduction of One

Laptop per Child foundation and its low-cost XO-1 laptop, the computing industry

started to pursue the price too. Although introduced only one year earlier, there were

14 million netbooks sold in 2008. Besides the regular computer manufacturers,

companies making especially rugged versions of computers have sprung up, offering

alternatives for people operating their machines in extreme weather or environments.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

3www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 4: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

1.2 Netbooks and nettops

The emergence of new market segment of small, energy-efficient and low-cost

devices (netbooks and nettops) could threaten established companies like Microsoft,

Intel, HP or Dell, analysts said in July 2008. A market research firm International

Data Corporation predicted that the category could grow from fewer than 500,000 in

2007 to 9 million in 2012 as the market for low cost and secondhand computers

expands in developed economies. Also, after Microsoft ceased selling of Windows

XP for ordinary machines, it made an exception and continued to offer the operating

system for netbook and nettop makers.

1.3 Mass storage

All computers require either fixed or removable storage for their operating system,

programs and user generated material.

Formerly the 5 1/4 inch and 3 1/2 inch floppy drive were the principal forms of

removable storage for backup of user files and distribution of software.

As memory sizes increased, the capacity of the floppy did not keep pace; the Zip drive

and other higher-capacity removable media were introduced but never became as

prevalent as the floppy drive.

By the late 1990s the optical drive, in CD and later DVD and Blu-ray Disc, became

the main method for software distribution, and writable media provided backup and

file interchange. Floppy drives have become uncommon in desktop personal

computers since about 2000, and were dropped from many laptop systems even

earlier.

Early home computers used compact audio cassettes for file storage; these were at the

time a very low cost storage solution, but were displaced by floppy disk drives when

manufacturing costs dropped, by the mid 1980s.

A second generation of tape recorders was provided when Videocassette recorders

were pressed into service as backup media for larger disk drives. All these systems

were less reliable and slower than purpose-built magnetic tape drives. Such tape

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

4www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 5: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

drives were uncommon in consumer-type personal computers but were a necessity in

business or industrial use.

Interchange of data such as photographs from digital cameras is greatly expedited by

installation of a card reader, which often is compatible with several forms of flash

memory. It is usually faster and more convenient to move large amounts of data by

removing the card from the mobile device, instead of communicating with the mobile

device through a USB interface.

A USB flash drive today performs much of the data transfer and backup functions

formerly done with floppy drives, Zip disks and other devices. Main-stream current

operating systems for personal computers provide standard support for flash drives,

allowing interchange even between computers using different processors and

operating systems. The compact size and lack of moving parts or dirt-sensitive media,

combined with low cost for high capacity, have made flash drives a popular and

useful accessory for any personal computer user.

The operating system (e.g.: Microsoft Windows, Mac OS, Linux or many others) can

be located on any removable storage, but typically it is on one of the hard disks. A

Live CD is also possible, but it is very slow and is usually used for installation of the

OS, demonstrations, or problem solving. Flash-based memory is currently expensive

(as of mid-2008) but is starting to appear in laptop computers because of its low

weight and low energy consumption, compared to hard disk storage.

2. Programming with C++

C++ ("C Plus Plus", pronounced /ˌsiːˌplʌsˈplʌs/) is a general-purpose programming language.

It is regarded as a middle-level language, as it comprises a combination of both high-level

and low-level language features. It was developed by Bjarne Stroustrup in 1979 at Bell Labs

as an enhancement to the C programming language and originally named "C with Classes". It

was renamed to C++ in 1983.

C++ is widely used in the software industry. Some of its application domains include systems

software, device drivers, embedded software, high-performance server and client

applications, and entertainment software such as video games. Several groups provide both

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

5www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 6: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

free and commercial C++ compiler software, including the GNU Project, Microsoft, Intel,

Borland and others.

The language began as enhancements to C, first adding classes, then virtual functions,

operator overloading, multiple inheritance, templates, and exception handling among other

features. After years of development, the C++ programming language standard was ratified in

1998 as ISO/IEC 14882:1998. The current standard is the 2003 version, ISO/IEC

14882:2003. The next standard version (known informally as C++0x) is in development.

C++ is a statically typed, free-form, multi-paradigm, compiled language where compilation

creates machine code for a target machine hardware.

2.1 Background

Stroustrup began work on C with Classes in 1979. The idea of creating a new

language originated from Stroustrup's experience in programming for his Ph.D. thesis.

Stroustrup found that Simula had features that were very helpful for large software

development, but the language was too slow for practical use, while BCPL was fast

but too low-level to be suitable for large software development. When Stroustrup

started working in AT&T Bell Labs, he had the problem of analyzing the UNIX

kernel with respect to distributed computing. Remembering his Ph.D. experience,

Stroustrup set out to enhance the C language with Simula-like features. C was chosen

because it was general-purpose, fast, portable and widely used. Besides C and Simula,

some other languages that inspired him were ALGOL 68, Ada, CLU and ML. At first,

the class, derived class, strong type checking, inlining, and default argument features

were added to C via Cfront. The first commercial release occurred in October 1985.

In 1983, the name of the language was changed from C with Classes to C++ (++

being the increment operator in C and C++). New features were added including

virtual functions, function name and operator overloading, references, constants, user-

controlled free-store memory control, improved type checking, and BCPL style

single-line comments with two forward slashes (//). In 1985, the first edition of The

C++ Programming Language was released, providing an important reference to the

language, since there was not yet an official standard. In 1989, Release 2.0 of C++

was released. New features included multiple inheritance, abstract classes, static

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

6www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 7: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

member functions, const member functions, and protected members. In 1990, The

Annotated C++ Reference Manual was published. This work became the basis for the

future standard. Late addition of features included templates, exceptions, namespaces,

new casts, and a Boolean type.

As the C++ language evolved, a standard library also evolved with it. The first

addition to the C++ standard library was the stream I/O library which provided

facilities to replace the traditional C functions such as printf and scanf. Later, among

the most significant additions to the standard library, was the Standard Template

Library.

C++ continues to be used and is still one of the preferred programming languages to

develop professional applications. The language has gone from being mostly Western,

to attracting programmers from all over the world.

3. Java

Java is a programming language originally developed by James Gosling at Sun Microsystems

and released in 1995 as a core component of Sun Microsystems' Java platform. The language

derives much of its syntax from C and C++ but has a simpler object model and fewer low-

level facilities. Java applications are typically compiled to bytecode that can run on any Java

virtual machine (JVM) regardless of computer architecture.

The original and reference implementation Java compilers, virtual machines, and class

libraries were developed by Sun from 1995. As of May 2007, in compliance with the

specifications of the Java Community Process, Sun made available most of their Java

technologies as free software under the GNU General Public License. Others have also

developed alternative implementations of these Sun technologies, such as the GNU Compiler

for Java and GNU Classpath.

One characteristic of Java is portability, which means that computer programs written in the

Java language must run similarly on any supported hardware/operating-system platform. One

should be able to write a program once, compile it once, and run it anywhere.

This is achieved by compiling the Java language code, not to machine code but to Java

bytecode instructions analogous to machine code but intended to be interpreted by a virtual

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

7www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 8: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

machine (VM) written specifically for the host hardware. End-users commonly use a Java

Runtime Environment (JRE) installed on their own machine for standalone Java applications,

or in a Web browser for Java applets.

Standardized libraries provide a generic way to access host specific features such as graphics,

threading and networking. In some JVM versions, bytecode can be compiled to native code,

either before or during program execution, resulting in faster execution.

A major benefit of using bytecode is porting. However, the overhead of interpretation means

that interpreted programs almost always run more slowly than programs compiled to native

executables would, and Java suffered a reputation for poor performance. This gap has been

narrowed by a number of optimisation techniques introduced in the more recent JVM

implementations.

One such technique, known as just-in-time (JIT) compilation, translates Java bytecode into

native code the first time that code is executed, then caches it. This results in a program that

starts and executes faster than pure interpreted code can, at the cost of introducing occasional

compilation overhead during execution. More sophisticated VMs also use dynamic

recompilation, in which the VM analyzes the behavior of the running program and selectively

recompiles and optimizes parts of the program. Dynamic recompilation can achieve

optimizations superior to static compilation because the dynamic compiler can base

optimizations on knowledge about the runtime environment and the set of loaded classes, and

can identify hot spots - parts of the program, often inner loops, that take up the most

execution time. JIT compilation and dynamic recompilation allow Java programs to approach

the speed of native code without losing portability.

Another technique, commonly known as static compilation, or ahead-of-time (AOT)

compilation, is to compile directly into native code like a more traditional compiler. Static

Java compilers translate the Java source or bytecode to native object code. This achieves

good performance compared to interpretation, at the expense of portability; the output of

these compilers can only be run on a single architecture. AOT could give Java something

close to native performance, yet it is still not portable since there are no compiler directives,

and all the pointers are indirect with no way to micro manage garbage collection.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

8www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 9: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Java's performance has improved substantially since the early versions, and performance of

JIT compilers relative to native compilers has in some tests been shown to be quite similar.

The performance of the compilers does not necessarily indicate the performance of the

compiled code; only careful testing can reveal the true performance issues in any system.

One of the unique advantages of the concept of a runtime engine is that errors (exceptions)

should not 'crash' the system. Moreover, in runtime engine environments such as Java there

exist tools that attach to the runtime engine and every time that an exception of interest

occurs they record debugging information that existed in memory at the time the exception

was thrown (stack and heap values). These Automated Exception Handling tools provide

'root-cause' information for exceptions in Java programs that run in production, testing or

development environments.

Topic : Primitive Data Types And Operations

Topic Objective:

At the end of this topic the student will be able to understand:

Types of data types

Data Operations

Definition/Overview:

Overview: A data type in programming languages is an attribute of a data which tells the

computer (and the programmer) something about the kind of data it is. This involves setting

constraints on the datum, such as what values it can take and what operations may be

performed upon it.In a broad sense, a data type defines a set of values and the allowable

operations on those values . Almost all programming languages explicitly include the notion

of data type, though different languages may use different terminology. Most programming

languages also allow the programmer to define additional data types, usually by combining

multiple elements of other types and defining the valid operations of the new data type. For

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

9www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 10: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

example, a programmer might create a new data type named "Person" that specifies that data

interpreted as Person would include a name and a date of birth.

For example, in the Java programming language, the "int" type represents the set of 32-bit

integers ranging in value from -2,147,483,648 to 2,147,483,647, as well as the operations that

can be performed on integers, such as addition, subtraction, and multiplication. Colors, on the

other hand, are represented by three bytes denoting the amounts each of red, green, and blue,

and one string representing that color's name; allowable operations include addition and

subtraction, but not multiplication.

A data type can also be thought of as a constraint placed upon the interpretation of data in a

type system, describing representation, interpretation and structure of values or objects stored

in computer memory. The type system uses data type information to check the correctness of

computer programs that access or manipulate the data.

Key Points:

1. Types of data types

1.1 Abstract data types (ADT )

In computing, an abstract data type (ADT) is a specification of a set of data and the

set of operations that can be performed on the data. Such a data type is abstract in the

sense that it is independent of various concrete implementations. The definition can

be mathematical, or it can be programmed as an interface. A first class ADT supports

the creation of multiple instances of the ADT, and the interface normally provides a

constructor, which returns an abstract handle to new data, and several operations,

which are functions accepting the abstract handle as an argument.

The main contribution of the abstract data type theory (and its evolution, the design

by contract) is that it (1) formalizes a definition of type (which was only intuitively

hinted on procedural programming) (2) on the basis of the information hiding

principle and (3) in a way that such formalization can be explicitly represented in

programming language notations and semantics. This important advance in computer

science theory (motivated by software engineering challenges in procedural

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

10www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 11: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

programming) led to the emergence of languages and methodological principles of

object-oriented programming.

1.2 Algebraic data type

In computer programming, an algebraic data type (sometimes also called a variant

type ) is a data type each of whose values is data from other data types wrapped in one

of the constructors of the data type. Any wrapped datum is an argument to the

constructor. In contrast to other data types, the constructor is not executed and the

only way to operate on the data is to unwrap the constructor using pattern matching.

The most common algebraic data type is a list with two constructors: Nil or [] for an

empty list, and Cons (an abbreviation of constructor), ::, or : for the combination of a

new element with a shorter list (for example (Cons 1 '(2 3 4)) or 1:).

Special cases of algebraic types are product types i.e. records (only one constructor)

and enumerated types (many constructors with no arguments). Algebraic types are

one kind of composite type (i.e. a type formed by combining other types).

An algebraic data type may also be an abstract data type (ADT) if it is exported from

a module without its constructors. Values of such a type can only be manipulated

using functions defined in the same module as the type itself.

In set theory the equivalent of an algebraic data type is a discriminated union a set

whose elements consist of a tag (equivalent to a constructor) and an object of a type

corresponding to the tag (equivalent to the constructor arguments).

1.3 Composite types

In computer science, composite types are data types which can be constructed in a

programming language out of that language's basic primitive types and other

composite types. The act of constructing a composite type is known as composition.

A struct is C's and C++'s notion of a composite type, a data type that composes a fixed

set of labeled fields or members. It is so called because of the struct keyword used in

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

11www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 12: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

declaring them, which is short for structure or, more precisely, user-defined data

structure.

In C++, the only difference between a struct and a class is the default access level,

which is private for classes and public for structs.

Note that while classes and the class keyword were completely new in C++, the C

programming language already had a crude type of structs. For all intents and

purposes, C++ structs form a superset of C structs: virtually all valid C structs are

valid C++ structs with the same semantics.

A struct declaration consists of a list of fields, each of which can have any type. The

total storage required for a struct object is the sum of the storage requirements of all

the fields, plus any internal padding.

1.4 Function types

Type signature is a term that is used in computer programming. A type signature

defines the inputs and outputs for a function or method. A type signature includes at

least the function name and the number of its parameters. In some programming

languages, it may also specify the function's return type or the types of its parameters.

Notice that the type of the result can be regarded as everything past the first supplied

argument. This is a consequence of currying. That is, given a function that had one

argument supplied, but takes in two inputs, the function is "curried" to produce a

function of one argument -- the one that is not supplied. Thus calling f(x), where f :: a

-> b -> c, yields a new function f' :: b -> c which can be called f'(b) to produce c.

The actual type specifications can consist of an actual type, such as Integer, or a

general type variable that is used in parametric polymorphic functions, such as "a", or

"b", or "anyType".

1.5 Machine data types

All data in computers based on digital electronics is represented as bits (alternatives 0

and 1) on the lowest level. The smallest addressable unit of data is a group of bits

called a byte (usually an octet, which is 8 bits). The unit processed by machine code

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

12www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 13: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

instructions is called a word (as of 2008, typically 32 or 64 bits). Most instructions

interpret the word as a binary number, such that a 32-bit word can represent unsigned

integer values from 0 to 232 − 1 or signed integer values from − 231 to 231− 1.

Because of two's complement, the machine language and machine don't need to

distinguish between these unsigned and signed data types for the most part.

There is a specific set of arithmetic instructions that use a different interpretation of

the bits in word as a floating-point number.

1.6 Object types

In its simplest embodiment, an object is an allocated region of storage. Since

programming languages use variables to access objects, the terms object and variable

are often used interchangeably. However, until memory is allocated, an object does

not exist.

All programming languages present objects. The presence of objects should not be

confounded with the concept of object-orientation.

In procedural programming, an object may contain data or instructions, but not both.

(Instructions may take the form of a procedure or function.) In object-oriented

programming, an object may be associated with both the data and the instructions that

operate on that data.

How an object is created depends on the language. In a prototype-based language

(e.g., JavaScript) an object can be created from nothing, or can be based on an

existing object. In a class-based language (e.g., Java), an object is created as an

instance (or instantiation) of a class. The class forms a specification for the object.

To give a real world analogy, a house is constructed according to a specification.

Here, the specification is a blueprint that represents a class, and the constructed house

represents the object.

In strictly mathematical branches of computer science the term object is used in a

purely mathematical sense to refer to any thing. While this interpretation is useful in

the discussion of abstract theory, it is not concrete enough to serve as a primitive data

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

13www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 14: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

type in the discussion of more concrete branches (such as programming) that are

closer to actual computation and information processing. Therefore, objects are still

conceptual entities, but generally correspond directly to a contiguous block of

computer memory of a specific size at a specific location. This is because

computation and information processing ultimately require a form of computer

memory. Objects in this sense are fundamental primitives needed to accurately define

concepts such as references, variables, and name binding. This is why the rest of this

article will focus on the concrete interpretation of an object rather than the abstract

one object oriented programming.

Note that although a block of computer memory can appear contiguous on one level

of abstraction and incontiguous on another, the important thing is that it appears

contiguous to the program that treats it as an object. That is, an object's private

implementation details must not be exposed to clients of the object, and they must be

able to change without requiring changes to client code. In particular, the size of the

block of memory that forms the object must be able to change without changes to

client code.

Objects exist only within contexts that are aware of them; a piece of computer

memory only holds an object if a program treats it as such (for example by reserving

it for exclusive use by specific procedures and/or associating a data type with it).

Thus, the lifetime of an object is the time during which it is treated as an object. This

is why they are still conceptual entities, despite their physical presence in computer

memory.

In other words, abstract concepts that do not occupy memory space at runtime are,

according to the definition, not objects; e.g., design patterns exhibited by a set of

classes, data types in statically typed programs.

1.7 Primitive types

In most programming languages, all basic types are built-in, but some composite

types may also be built-in. Opinions vary as to whether a built-in type that is not basic

should be considered "primitive".

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

14www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 15: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Depending on the language and its implementation, primitive types may or may not

have a one-to-one correspondence with objects in the computer's memory. However,

one usually expects operations on basic primitive types to be the fastest language

constructs there are. Integer addition, for example, can be performed as a single

machine instruction, and some processors offer specific instructions to process

sequences of characters with a single instruction. In particular, the C standard

mentions that "a 'plain' int object has the natural size suggested by the architecture of

the execution environment". This means that int is likely to be 32 bits long on a 32-bit

architecture. Basic primitive types are almost always value types.

Most languages do not allow the behaviour or capabilities of primitive (either built-in

or basic) types to be modified by programs. Exceptions include Smalltalk, which

permits all data types to be extended within a program, adding to the operations that

can be performed on them or even redefining the built-in operations.

A character type (typically called "char") may contain a single letter, digit,

punctuation mark, or control character. Some languages have two or more character

types, for example a single-byte type for ASCII characters and a multi-byte type for

Unicode characters. The term "character type" is normally used even for types whose

values more precisely represent code units, for example a UTF-16 code unit as in Java

and JavaScript.

Characters may be combined into strings. The string data can include numbers and

other numerical symbols but will be treated as text. In most languages, a string is

equivalent to an array of characters or code units, but Java treats them as distinct types

(java.lang.String and char[]). Other languages (such as Python, and many dialects of

BASIC) have no separate character type; strings with a length of one are normally

used to represent (single code unit) characters. Literals for characters and strings are

usually surrounded by quotation marks: sometimes, single quotes (') are used for

characters and double quotes (") are used for strings.

2. Data Operations

Programming languages generally support a set of operators that are similar to operators in

mathematics. A language may contain a fixed number of built-in operators (e.g., C

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

15www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 16: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

programming language) or it may allow the creation of programmer-defined operators (e.g.,

C++).

Some built-in operators supported by a language have a direct mapping to a small number of

instructions commonly found on central processing units, though others (e.g. '+' used to

express string concatenation) may have complicated implementations. The specification of a

language will specify the precedence and associativity of the operators it supports. Most

programming language operators take one or two operands, with a few supporting more

operands (e.g., the ?: operator in C). The position of the operator with respect to its operands

may be prefix, infix or postfix.

2.1 Operator overloading

In some programming languages an operator may be ad-hoc polymorphic, that is,

have definitions for more than one kind of data, (such as in Java where the + operator

is used both for the addition of numbers and for the concatenation of strings). Such an

operator is said to be overloaded. In languages that support operator overloading by

the programmer but have a limited set of operators, such as C++, operator overloading

is often used to define customized uses for operators.

2.2 Operand coercion

Some languages also allow for the operands of an operator to be implicitly converted

or coerced to suitable data types for the operation to occur. For example, in Perl

coercion rules lead into 12 + "3.14" producing the result of 15.14. The text "3.14" is

converted to the number 3.14 before addition can take place. Further, 12 is an integer

and 3.14 is either a floating or fixed-point number (a number that has a decimal place

in it) so the integer is then converted to a floating point or fixed-point number

respectively.

In the presence of coercions in a language, the programmer must be aware of the

specific rules regarding operand types and the operation result type to avoid subtle

programming mistakes.

In computer science, type conversion or typecasting refers to changing an entity of

one data type into another. This is done to take advantage of certain features of type

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

16www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 17: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

hierarchies. For instance, values from a more limited set, such as integers, can be

stored in a more compact format and later converted to a different format enabling

operations not previously possible, such as division with several decimal places'

worth of accuracy. In object-oriented programming languages, type conversion allows

programs to treat objects of one type as one of their ancestor types to simplify

interacting with them.

There are two types of conversion: implicit and explicit. The term for implicit type

conversion is coercion. The most common form of explicit type conversion is known

as casting. Explicit type conversion can also be achieved with separately defined

conversion routines such as an overloaded object constructor.

2.3 Operators in APL

In the Iverson Notation that later became APL, Kenneth E. Iverson defined several

operators (reduction, inner product, outer product) acting on functions to produce

functions. So, for example, +/ (plus-reduce) applies the reduction operator to the

binary function + to create a function for adding vectors, rows of matrices, etc.

APL (A Programming Language) is an array programming language based on a

notation invented in 1957 by Kenneth E. Iverson while at Harvard University. It

originated as an attempt to provide consistent notation for the teaching and analysis of

topics related to the application of computers. Iverson published his notation in 1962

in a book titled A Programming Language. By 1965, a subset of the notation was

implemented as a programming language, then known as IVSYS. Later, prior to its

commercial release, APL got its name from the title of the book. Iverson received the

Turing Award in 1979 for his work.

Iverson's notation was later used to describe the IBM System/360 machine

architecture, a description much more concise and exact than the existing

documentation and revealing several previously unnoticed problems. Later, a

Selectric typeball was specially designed to write a linear representation of this

notation. This distinctive aspect of APL, the use of a special character set visually

depicting the operations to be performed, remains fundamentally unchanged today.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

17www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 18: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

The APL language features a rich set of operations which work on entire arrays of

data, like the vector instruction set of a SIMD architecture. While many computer

languages would require iteration to, for example, add two arrays together, functions

in APL typically deal with entire arrays at once. In conjunction with a special

character set where glyphs represent operations to be performed, this drastically

reduces the potential number of loops and allows for smaller, more concise and

compact programs.

As with all programming languages that have had several decades of continual use,

APL has evolved significantly, generally in an upward-compatible manner, from its

earlier releases. APL is usually interpretive and interactive, and normally features a

read-evaluate-print loop (REPL) for command and expression input. Today, nearly all

modern implementations support structured programming while several dialects now

feature some form of object oriented programming constructs.

Topic : Selection Statements

Topic Objective:

At the end of this topic the student will be able to understand:

Simple Statements

Compound Statements

Definition/Overview:

Overview: In computer programming a statement can be thought of as the smallest

standalone element of an imperative programming language. A program is formed by a

sequence of one or more statements. A statement will have internal components (e.g.,

expressions). Many languages (e.g. C) make a distinction between statements and definitions,

with a statement only containing executable code and a definition declaring an identifier. A

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

18www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 19: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

distinction can also be made between simple and compound statements; the latter may

contain statements as components.

Key Points:

1. Simple statements

1.1 Assignment

In computer science the assignment statement sets or re-sets the value stored in the

storage location(s) denoted by a variable name. In most imperative computer

programming languages the assignment statement is one of the basic statements. The

assignment statement often allows that the same variable name to contain different

values at different times during program execution.

In most expression-oriented programming languages, the assignment statement

returns the assigned value, allowing such idioms as x = y = a, which assigns the value

of a to both x and y, and while (f = read()) {}, which uses the return value of a

function to control a loop while assigning that same value to a variable. In other

programming languages, the return value of an assignment is undefined and such

idioms are invalid. An example is Scheme. In Python, assignment is not an

expression, and thus has no "value".

In Haskell, there is no variable assignment; but operations similar to assignment (like

assigning to a field of an array or a field of a mutable data structure) usually evaluate

to unit, the value of the unit type, which is typically the type of an expression that is

evaluated purely for its side effects.

In functional programming, assignment is discouraged in favor of single assignment,

also called name binding or initialization. Single assignment differs from assignment

as described in this article in that it can only be made once, usually when the variable

is created; no subsequent re-assignment is allowed. Once created by single

assignment, named values are not variables but immutable objects.

Single assignment is the only form of assignment available in purely functional

languages, such as Haskell, which do not have variables in the sense of imperative

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

19www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 20: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

programming languages. Impure functional languages provide both single assignment

as well as true assignment (though true assignment is used with less frequency than in

imperative programming languages). For example, in Scheme, both single assignment

and true assignment can be used on all variables. In OCaml, only single assignment is

allowed for variables, via the let name = value syntax; however, true assignment, by a

separate <- operator, can be used on elements of arrays and strings, as well as fields of

records and objects that have been explicitly declared mutable (meaning capable of

being changed after its initial declaration) by the programmer.

Beginning programmers sometimes confuse assignment with the relational operator

for equality, as "=" means equality in mathematics, and is used for assignment in

many languages. But assignment alters the value of a variable, while equality testing

tests whether two expressions have the same value. In many languages, the

assignment operator is a single equals sign ("=") while the equivalence operator is a

pair of equals signs ("=="); in some languages, such as BASIC, a single equals sign is

used for both, with context determining which is meant.

This can lead to errors if the programmer forgets which form (=, ==, :=) is appropriate

(or mistypes = when == was intended). This is a common programming problem with

languages such as C, where the assignment operator also returns the value assigned,

and can be validly nested inside expressions (in the same way that a function returns a

value). If the intention was to compare two values in an if statement, for instance, an

assignment is quite likely to return a value interpretable as TRUE, in which case the

then clause will be executed, leading the program to behave unexpectedly. Some

language processors can detect such situations, and warn the programmer of the

potential error.

1.2 Subroutine

In computer science, a subroutine or subprogram (also called procedure, function,

method, or routine) is a portion of code within a larger program, which performs a

specific task and is relatively independent of the remaining code. (The name

"method" is mostly used in object-oriented programming, specifically for subroutines

that are part of objects or object classes.)

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

20www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 21: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

As the name suggests, a subprogram or subroutine behaves in much the same way as a

complete computer program that is used as a step in a larger program. A subroutine is

often coded so that it can be executed (called) several times and/or from several

places during a single execution of the program, including from other subroutines, and

branch back (return) to the point after the call once its task is done.

Subroutines are a powerful programming tool , and the syntax of many programming

languages includes support for writing and using them. Judicious use of subroutines

(for example, though the structured programming approach) will often substantially

reduce the cost of developing and maintaining a large program, while increasing its

quality and reliability . Subroutines, often collected into libraries, are an important

mechanism for sharing and trading software.

Most modern implementations use a call stack, a special case of the stack data

structure, to implement subroutine calls and returns. Each procedure call creates a

new entry, called a stack frame, at the top of the stack; when the procedure returns, its

stack frame is deleted from the stack, and its space may be used for other procedure

calls. Each stack frame contains the private data of the corresponding call, which

typically includes the procedure's parameters and internal variables, and the return

address. The call sequence can be implemented by a sequence of ordinary instructions

(an approach still used in RISC and VLIW architectures), but many traditional

machines designed since the late 1960s have included special instructions for that

purpose.

The call stack is usually implemented as a contiguous area of memory. It is an

arbitrary design choice whether the bottom of the stack is the the lowest or highest

address within this area, so that the stack may grow forwards or backwards in

memory; however, many architectures chose the latter.

Some designs, notably some Forthimplementations, used two separate call stacks, one

mainly for control information (like return addresses and loop counters) and the other

for data.

When stack-based procedure calls were first introduced, an important motivation was

to save precious memory. With this scheme, the compiler does not have to reserve

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

21www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 22: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

separate space in memory for the private data (parameters, return address, and local

variables) of each procedure. At any moment, the stack contains only the private data

of the calls that are currently active (namely, which have been called but haven't

returned yet). Because of the ways in which programs were usually assembled from

libraries, it was (and still is) not uncommon to find programs which include thousands

of subroutines, of which only a handful are active at any given moment. For such

programs, the call stack mechanism could save significant amounts of memory.

Indeed, the call stack mechanism can be viewed as the earliest and simplest method

for automatic memory management.

However, another advantage of the call stack method is that it allows recursive

subroutine calls, since each nested call to the same procedure gets a separate instance

of its private data.

1.3 Return statement

In computer programming, a return statement causes execution to leave the current

subroutine and resume at the point in the code immediately after where the subroutine

was called known as its return address. The return address is saved, usually on the

process's call stack, as part of the operation of making the subroutine call. Return

statements in many languages allow a function to specify a return value to be passed

back to the code that called the function.

In C/C++, return exp; (where exp is an expression) is a statement that tells a function

to return execution of the program to the calling function, and report the value of exp.

If a function does not have a return type (i.e., its return type is void), the return

statement can be used without a value, in which case the program just breaks out of

the current function and returns to the calling one.

In Pascal there is no return statement. A subroutine automatically returns when

execution reaches its last executable statement. Values may be returned by assigning

to an identifier that has the same name as the subroutine (a function in Pascal

terminology).

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

22www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 23: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Certain programming languages, such as Perl and Ruby allow the programmer to omit

an explicit return statement, specifying instead that the last evaluated expression is the

return value of the subroutine. In Windows PowerShell all evaluated expressions

which are not captured (e.g. assigned to a variable, cast to void or piped to $null) are

returned from the subroutine as elements in an array, or as a single object in the case

that only one object has not been captured.

1.4 Goto

GOTO is a statement found in many computer programming languages. It is a

combination of the English words go and to. When executed it causes an

unconditional transfer of control (a "jump") to another statement. The jumped-to

statement is specified using some kind of label, which may be an identifier or a line

number depending on the language. At the machine code level a goto is a form of

branch or jump statement.

In some languages, goto functionality may be present without explicit use of the

keyword goto, such as where a break or continue keyword may be followed by an

identifier denoting a label. The SNOBOL programming language supports a form of

statement suffix which causes an unconditional transfer of control after the statement

has finished executing.

While GOTO statements are found in most high-level languages, there are a few high-

level languages that do not support them. For instance, Java (where goto is a reserved

word but does not presently serve any function).

The GOTO statement has been the target of much continued criticism and debate,

with the primary negative claim being that use of GOTO results in unreadable and

generally unmaintainable "spaghetti code". As structured programming became more

popular in the 1960s and 1970s, many computer scientists came to the conclusion that

programs should always use so-called 'structured' flow-control commands such as

loops and if-then-else statements in place of GOTO. Even today some programming

style coding standards forbid the use of GOTO statements using similar rationales. In

defense of GOTO statements, others have noted that the restrained use of GOTO does

not necessarily lead to poor quality code, and also argue that there are some tasks that

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

23www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 24: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

cannot be straightforwardly accomplished in many programming languages without

the use of one or more GOTO statements, such as implementing finite state machines,

breaking out of nested loops and exception handling.

Probably the most famous criticism of GOTO is a 1968 letter by Edsger Dijkstra

called Go To Statement Considered Harmful. In that letter Dijkstra argued that

unrestricted GOTO statements should be abolished from higher-level languages

because they complicated the task of analyzing and verifying the correctness of

programs (particularly those involving loops). An alternative viewpoint is presented

in Donald Knuth's Structured Programming with go to Statementswhich analyzes

many common programming tasks and finds that in some of them GOTO is the

optimal language construct to use.

This criticism had an effect on the design of some programming languages. Although

the designers of the Ada language in the late 1970s were aware of the criticisms of

GOTO, the statement was still included in the language, mainly to support

automatically generated code where the goto might prove indispensable. However, the

labels used as the destination of a goto statement take the unusual form of an

identifier enclosed in double angle brackets (e.g.<< Start_Again>>) and this syntax is

not used anywhere else in the language. This makes it easy to check a program for the

existence of goto destinations.

1.5 Assertion

In computer programming, an assertion is a predicate (i.e., a truefalse statement)

placed in a program to indicate that the developer thinks that the predicate is always

true at that place.

Assertions can be a form of documentation: they can describe the state the code

expects to find before it runs (its preconditions), and the state the code expects to

result in when it is finished running (postconditions); they can also specify invariants

of a class. In Eiffel, such assertions are integrated into the language and are

automatically extracted to document the class. This forms an important part of the

method of design by contract.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

24www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 25: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

This approach is also useful in languages that do not explicitly support it: the

advantage of using assertion statements rather than assertions in comments is that

assertions can be checked every time the program is run; if the assertion no longer

holds, an error can be reported. This prevents the code from getting out of sync with

the assertions (a problem that can occur with comments).

In Java, % is the remainder operator (not modulus) if its first operand is negative, the

result can also be negative. Here, the programmer has assumed that total is non-

negative, so that the remainder of a division with 2 will always be 0 or 1. The

assertion makes this assumption explicit if countNumberOfUsers does return a

negative value, it is likely a bug in the program.

A major advantage of this technique is that when an error does occur it is detected

immediately and directly, rather than later through its often obscure side-effects.

Since an assertion failure usually reports the code location, one can often pin-point the

error without further debugging.

Assertions are also sometimes placed at points the execution is not supposed to reach.

For example, assertions could be placed at the default clause of the switch statement

in languages such as C, C++, and Java. Cases that are intentionally not handled by the

programmer will raise an error and abort the program rather than silently continuing

in an erroneous state.

In Java, assertions have been a part of the language since version 1.4. Assertion

failures result in raising an AssertionError when the program is run with the

appropriate flags, without which the assert statements are ignored. In C, they are

added on by the standard header assert.h defining assert (assertion) as a macro that

signals an error in the case of failure, usually terminating the program. In standard

C++ the header cassert is required instead. However, some C++ libraries still have the

assert.h available.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

25www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 26: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

2. Compound statements

2.1 Statement block

In computer programming, a statement block (or code block) is a section of code

which is grouped together, much like a paragraph; such blocks consist of one, or

more, statements. Statement blocks help make code more readable by breaking up

programs into logical work units.

In C, C++, Java and some other languages, statement blocks are enclosed by curly

braces {}. In Algol, Pascal, Ada, and some other languages, they are denoted by

"begin" and "end" statements. In Python they are indicated by indentation (the Off-

side rule). Unlike paragraphs, statement blocks can be nested; that is, with one block

inside another. Blocks often define the scope of the identifiers used within.

Blocks become more independent when they can have their own variables, i.e. if

identifiers defined inside a block cannot be referred to from outside that block.

Languages without lexical scoping such as Javascript and Pico cannot support this in

principle, but many languages with lexical scoping still don't support it for nested

blocks (e.g., some dialects of C, C#), while others do (e.g. Algol 68, other dialects of

C, VB.NET).

In C++, blocks can be used to define object lifetime (creation and destruction). In

languages such as Smalltalk, blocks are objects in their own right, extended with a

reference to their environment of definition, i.e. closures.

2.2 Conditional

In computer science, conditional statements, conditional expressions and conditional

constructs are features of a programming language which perform different

computations or actions depending on whether a programmer-specified condition

evaluates to true or false (see boolean data type). Apart from the case of branch

predication, this is always achieved by selectively altering the control flow based on

some condition.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

26www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 27: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

In imperative programming languages, the term "conditional statement" is usually

used, whereas in functional programming, the terms "conditional expression" or

"conditional construct" are preferred, because these terms all have distinct meanings.

Although dynamic dispatch is not usually classified as a conditional construct, it is

another way to select between alternatives at runtime.

When an interpreter finds an If, it expects a boolean condition - for example, x > 0,

which means "the variable x contains a number that is greater than zero" - and

evaluates that condition. If the condition is true, the statement block following the

Then is executed. Otherwise, the execution continues in the following block - either in

the Else block (which is usually optional), or if there is no Else block, then after the

End If.

After either the block after the Then or the block after the Else has been executed,

control returns to the point after the End If.

In early programming languages - and in particular, in some dialects of BASIC in the

1980s - an if-then statement could only contain GOTO statements. This led to a hard-

to-read style of programming known as spaghetti programming. As a result,

structured programming, which allowed (virtually) arbitrary statements to be put in

statement blocks inside an if statement, gained in popularity, until it became the norm.

Many languages support if expressions, which are similar to if statements, but return a

value as a result. Thus, they are true expressions (which evaluate to a value), not

statements (which just perform an action).

2.3 Switch statement

In computer programming, a switch statement is a type of control statement that exists

in most modern imperative programming languages (e.g., Pascal, C, C++, C#, and

Java). Its purpose is to allow the value of a variable or expression to control the flow

of program execution. In some other programming languages, a statement that is

syntactically different but conceptually the same as the switch statement is known as a

case statement or a select statement.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

27www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 28: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

In most languages, a switch statement is defined across many individual statements. A

typical syntax is that the first line contains the actual word "switch" followed by either

the name of a variable or some other expression allowed by the language's syntax.

This variable or expression is usually referred to as the "control variable" of the

switch statement. After this line, following lines define one or more blocks of code

that represent possible branches that program execution may take.

Each block begins with a line containing the case keyword followed by a value that

the control variable may have. If the value of the control variable matches this value,

program execution will jump to that block of code. If not, the value specified in the

next block (if present) is examined and the process repeats.

An optional special block is also allowed, which does not specify any value and

which begins with the default keyword instead of the case keyword. If this block is

present and if none of the values listed for any other block matches that of the control

variable, program execution will jump to the statement following the default keyword.

The method of terminating a block is also of note. Typically, a break keyword is used

to signal the end of the block. When encountered, this keyword causes program

execution to continue with the first statement after the series of statements within the

switch statement, thus completing execution of the switch statement. If no break

keyword is present at the end of the block, in many languages program execution

"falls through" to the code associated with the next block in the switch statement, as if

its value also matched the value of the control variable. Notable exceptions include

C#, in which fallthrough is not permitted unless the block is empty and all blocks

must be terminated via a break, or by using another keyword. Similarly, almost all

BASIC dialects that feature this type of statement do not allow fallthrough.

One alternative to a switch statement can be the use of a lookup table which contains

as keys the case values and as values the part under the case statement. In some

languages, only actual data types are allowed as values in the lookup table. In other

languages, it is also possible to assign functions as lookup table values, gaining the

same flexibility as a real switch statement (this is one way to implement switch

statements in Lua which has no built-in switch ).

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

28www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 29: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

In some cases, lookup tables are more efficient than switch statements as many

languages can optimize the table lookup whereas switch statements are often not

optimized that much. A non-optimized, non-binary search lookup however will

almost certainly be slower than either a non-optimized switch (or the equivalent

multiple if-else statements).

Another "alternative" to switch statements is the extensive use of polymorphism.

2.4 While loop

In most computer programming languages, a while loop is a control flow statement

that allows code to be executed repeatedly based on a given boolean condition. The

while loop can be thought of as a repeating if statement. The while construct consists

of a block of code and a condition. The condition is evaluated, and if the condition is

true, the code within the block is executed. This repeats until the condition becomes

false. Because while loops check the condition before the block is executed, the

control structure is often also known as a pre-test loop. Compare with the do while

loop, which tests the condition after the loop has executed. For example, in the C

programming language (as well as Java and C++, which use the same syntax in this

case), the code fragment

2.5 Do while loop

In most computer programming languages, a do while loop, sometimes just called a

do loop, is a control flow statement that allows code to be executed repeatedly based

on a given Boolean condition. Note though that unlike most languages, Fortran's do

loop is actually analogous to the for loop.

The do while construct consists of a block of code and a condition. First, the code

within the block is executed, and then the condition is evaluated. If the condition is

true the code within the block is executed again. This repeats until the condition

becomes false. Because do while loops check the condition after the block is

executed, the control structure is often also known as a post-test loop. Contrast with

the while loop, which tests the condition before the code within the block is executed.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

29www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 30: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

It is possible, and in some cases desirable, for the condition to always evaluate to true,

creating an infinite loop. When such a loop is created intentionally, there is usually

another control structure (such as a break statement) that allows termination of the

loop.

Some languages may use a different naming convention for this type of loop. For

example, the Pascal language has a "repeat until" loop, which continues to run until

the control expression is true (and then terminates) whereas a "do-while" loop runs

while the control expression is true (and terminates once the expression becomes

false).

2.6 For loop

In computer science a for loop is a programming language statement which allows

code to be repeatedly executed. A for loop is classified as an iteration statement.

Unlike many other kinds of loops, such as the while loop, the for loop is often

distinguished by an explicit loop counter or loop variable. This allows the body of the

for loop (the code that is being repeatedly executed) to know about the sequencing of

each iteration. For loops are also typically used when the number of iterations is

known before entering the loop.

The name for loop comes from the English word for, which is used as the keyword in

most programming languages to introduce a for loop.

The loop body is executed "for" the given values of the loop variable, though this is

more explicit in the ALGOL version of the statement, in which a list of possible

values and/or increments can be specified. In FORTRAN and PL/I though, the

keyword DO is used and it is called a do loop, but it is otherwise identical to the for

loop described here.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

30www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 31: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Topic : Loops

Topic Objective:

At the end of this topic the student will be able to understand:

Kinds of Loops

Additional semantics and constructs

Distinguishing iterator-based and numeric for loops

Definition/Overview:

Overview: In computer science a for loop is a programming language statement which

allows code to be repeatedly executed. A for loop is classified as an iteration statement.

Unlike many other kinds of loops, such as the while loop, the for loop is often distinguished

by an explicit loop counter or loop variable. This allows the body of the for loop (the code

that is being repeatedly executed) to know about the sequencing of each iteration. For loops

are also typically used when the number of iterations is known before entering the loop. The

name for loop comes from the English word for, which is used as the keyword in most

programming languages to introduce a for loop. The loop body is executed "for" the given

values of the loop variable, though this is more explicit in the ALGOL version of the

statement, in which a list of possible values and/or increments can be specified. In

FORTRAN and PL/I though, the keyword DO is used and it is called a do loop, but it is

otherwise identical to the for loop described here.

Key Points:

1. Kinds of for loops

A for loop statement is available in most imperative programming languages. Even ignoring

minor differences in syntax there are many differences in how these statements work and the

level of expressiveness they support. Generally, for loops fall into one of the following

categories:

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

31www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 32: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

1.1 Numeric ranges

This type of for loop is characterized by counting; enumerating each of the values

within a numeric integer range, or arithmetic progression. The range is often specified

by a beginning and ending number, and sometimes may include a step value (allowing

one to count by two's or to count backwards for instance).

The loop variable I will take on the values 1, 2, ..., 9, 10 through each of the ten

iterations of the loop's body, which will be executed in that order. Each computer

language and even different dialects of the same language (e.g. BASIC) has its own

syntax keywords and means of specifying the start stop and step values. A rarely-

available generalisation allows the start stop and step values to be specified as items

in a list, not just a single arithmetic sequence. Where each item in the list might itself

be an arithmetic sequence. An ordinary for loop is thus an example of a list with only

one element.

1.2 Iterator-based for loops

This type of for loop is a generalization of the numeric range type of for loop; as it

allows for the enumeration of sets of items other than number sequences. It is usually

characterized by the use of an implicit or explicit iterator, in which the loop variable

takes on each of the values in a sequence or other orderable data collection. Where

some_iterable_object is either a data collection that supports implicit iteration, or may

in fact be an iterator itself. Some languages have this in addition to another for-loop

syntax; notably, PHP has this type of loop under the name foreach, as well as a three-

expression for loop (see below) under the name for.

1.3 Compound For loops

Introduced with ALGOL 68 and followed by PL/I, this allows the iteration of a loop

to be compounded with a test, as in: for i:=1:N while A(i) > 0 do etc.

That is, a value is assigned to the loop variable i, and only if the while expression is

true will the loop body be executed. If the result were false the for-loop's execution

stops short. Granted that the loop variable's value is defined after the termination of

the loop, then the above statement will find the first non-positive element in array A

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

32www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 33: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

(and if no such, its value will be N+1), or, with suitable variations, the first non-blank

character in a string, and so on.

1.4 Three-expression for loops

This type of for loop is found in nearly all languages which share a common heritage

with the C programming language. It is characterized by a three-parameter loop

control expression; consisting of an initializer, a loop-test, and a counting expression.

The three control expressions, separated by semicolons here, are from left to right the

initializer expression, the loop test expression, and the counting expression. The

initializer is evaluated exactly once right at the beginning. The loop test expression is

evaluated at the beginning of each iteration through the loop, and determines when the

loop should exit. Finally, the counting expression is evaluated at the end of each loop

iteration, and is usually responsible for altering the loop variable.

In most languages which provide this type of for loop, each of the three control loop

expressions is optional. When omitted the loop test expression is taken to always be

true, while the initializer and counting expressions are treated as no-ops when

omitted. The semicolons in the syntax are sufficient to indicate the omission of one of

the expressions.

2. Additional semantics and constructs

2.1 Use as infinite loops

This C-style for loop is commonly the source of an infinite loop since the fundamental

steps of iteration are completely in the control of the programmer. In fact when

infinite loops are intended, this type of for loop is often used with empty expressions.

2.2 Early exit and continuation

Some languages may also provide other supporting statements, which when present

can alter how the for loop iteration proceeds. Common among these are the break and

continue statements found in C and its derivatives. The break statement causes the

inner-most loop to be terminated immediately when executed. The continue statement

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

33www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 34: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

will move at once to the next iteration without further progress through the loop body

for the current iteration. Other languages may have similar statements or otherwise

provide means to alter the for loop progress.

Unfortunately, the clear lead given by BASIC has not been followed, and so the END

DO does not identify the loop variable it is thought to belong with, and worse, nor do

the CYCLE and EXIT statements. This becomes much more important when many

and nested loops are involved. The EXIT could even be taken to mean exit the

procedure instead of exit the loop: phrases such as NEXT I and possibly, DONEXT I

and DOQUIT I or similar explicit indications would help make blunders more

apparent. A partial solution is offered through a syntax extension (in Fortran and PL/I

for example) whereby a label is associated with the DO statement, and the same label

text is appended to the end marker, such as x:DO I = 1,N and END DO x in the

example, whereupon CYCLE x and EXIT x could be used. However, working

directly against the objective, the text of the label x is not allowed to be the name of

the loop variable, so "I" would not be allowed (though "II" would be), and, if there is

a second such loop later in the routine, different label texts would have to be chosen.

2.3 Loop variable scope and semantics

Different languages specify different rules for what value the loop variable will hold

on termination of its loop, and indeed some hold that it "becomes undefined". This

permits a compiler to generate code that leaves any value in the loop variable, or

perhaps even leaves it unchanged because the loop value was held in a register and

never stored to memory.

In some languages, (not C or C++) the loop variable is immutable within the scope of

the loop body, with any attempt to modify its value being regarded as a semantic

error. Such modifications are sometimes a consequence of a programmer error, which

can be very difficult to identify once made. However, only overt changes are likely to

be detected by the compiler. Situations where the address of the loop variable is

passed as an argument to a subroutine make it very difficult to check, because the

routine's behaviour is in general unknowable to the compiler.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

34www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 35: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Still another possibility is that the code generated may employ an auxiliary variable as

the loop variable, possibly held in a machine register, whose value may or may not be

copied to I on each iteration. In this case, modifications of I would not affect the

control of the loop, but now a disjunction is possible: within the loop, references to

the value of I might be to the (possibly altered) current value of I or to the auxiliary

variable (held safe from improper modification) and confusing results are guaranteed.

For instance, within the loop a reference to element I of an array would likely employ

the auxiliary variable (especially if it were held in a machine register), but if I is a

parameter to some routine (for instance, a print-statement to reveal its value), it would

likely be a reference to the proper variable I instead. It is best to avoid such

possibilities.

3. Distinguishing iterator-based and numeric for loops

A language may offer both an iterator-based for loop and a numeric-based for loop in of

course their own syntax. It may appear that a numeric-based loop may always be replaced by

an appropriate iterator-based loop, but differences can arise. Suppose an array A has elements

1 to N and the language does not offer a simple assignment statement A:=3*A; so that some

sort of for-loop must be devised.

Which are clearly equivalent, indeed the differences seem mere syntax trivia, but, the

semantics are different. The forall version is to be regarded as a mass assignment where

notionally, all the right-hand side results are evaluated and left-hand side recipients are

located, then the assignments are done. The code the compiler devises to effect this is

unstated, but the idea is that no item on the left-hand side is changed before all items on the

right-hand side are evaluated; every element is assigned to once only.

Now suppose that the requirement is that each element of A is to be the average of itself and

its two neighbours, and for simplicity, suppose that the first and last elements are to be

unchanged.

In this case, the results will be different: because the for loop is executed as successive

iterations, element A(i-1) will hold the value that had just been calculated by the previous

iteration, not the original value, while in the forall version, it would not yet have been

changed. Provided of course that the compiler's implementation of the forall construct does in

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

35www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 36: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

fact uphold that interpretation. This difference may or may not be important. If not,

whichever runs fastest could be chosen. But the difference can be vital, as in certain stages of

the LU decomposition algorithm for just one example.

More complex for loops (especially with conditional branching) will introduce further

difficulties unlikely to be accommodated by the syntax of the forall statement. Rather than

trying to convert a for statement into a forall statement, the task should be recast in terms of

the assignment of one data structure (such as an array) to another of the same type, avoiding

complex conditions.

These statements will typically implicitly increment the counter of a for loop, but not the

equivalent while loop (since in the latter case the counter is not an integral part of the loop

construct). Any translation will have to place all such statements within a block that

increments the explicit counter before running the statement.

Topic : Methods

Topic Objective:

At the end of this topic the student will be able to understand:

Kinds of methods

Isolation levels

Some recommended usages

Virtual inheritance

Definition/Overview:

Overview: In object-oriented programming, the term method refers to a subroutine that is

exclusively associated either with a class (called class methods or static methods) or with an

object (called instance methods). Like a procedure in procedural programming languages, a

method usually consists of a sequence of statements to perform an action, a set of input

parameters to customize those actions, and possibly an output value (called return value) of

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

36www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 37: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

some kind. Methods can provide a mechanism for accessing (for both reading and writing)

the encapsulated data stored in an object or a class.

Key Points:

1. Kinds of methods

As stated above, instance methods are associated with a particular object, while class or static

methods are instead associated with a class. In all typical implementations, instance methods

are passed a hidden Reference (computer science) (e.g. this, self or Me) to the object

(whether a class or class instance) they belong to, so that they can access the data associated

with it. For class/static methods, this may or may not happen according to the language; A

typical example of a class method would be one that keeps count of the number of created

objects within a given class.

An abstract method is a dummy code method which has no implementation. It is often used

as a placeholder to be overridden later by a subclass of or an object prototyped from the one

that implements the abstract method. In this way, abstract methods help to partially specify a

framework.

An accessor method is a method that is usually small, simple and provides the means for the

state of an object to be accessed from other parts of a program. Although it introduces a new

dependency, use of the methods are preferred to directly accessing state data because they

provide an abstraction layer. For example, if a bank-account class provides a getBalance()

accessor method to retrieve the current balance (rather than directly accessing the balance

data fields), then later revisions of the same code can implement a more complex mechanism

balance retrieval (say, a database fetch) without the dependent code needing to be changed. A

method that changes the state of an object is no longer called an accessor method, but rather

an update method, a modifier method, or a mutator method. Objects that provide such

methods are considered mutable objects.

Many languages support methods that are called automatically upon the creation of an

instance of a class, known as a Constructors. Some languages have a special syntax for

constructors. In Java, C++, C#, ActionScript, and PHP they have the same name as the class

of which they are a member (PHP 5 also allows __construct as a constructor); in Visual Basic

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

37www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 38: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

.NET the constructor is called New. Object Pascal constructors are signified by the keyword

constructor and can have user-defined names (but are mostly called Create). Under

Objective-C, the constructor method is split between two methods, alloc and init, with the

alloc method setting aside memory for an instance of the class and the init method handling

the bulk of initializing the instance; a call to the new method invokes both the alloc and the

init method for the class instance.

Likewise, some languages have special Destructor methods, i.e. instance methods that are

called automatically upon the destruction of an instance of a class. In C++, they are

distinguished by having the same name as the class of the object they're associated with, but

with the addition of a tilde (~) in front (or __destruct in PHP 5). In Object Pascal destructors

have the keyword destructor and can have user-defined names (but are mostly called

Destroy). Under Objective-C, the destructor method is named dealloc.

2. Isolation levels

Whereas a C programmer might push a value onto a stack data-structure by calling:

stackPush(&myStack, value);

a C++ programmer would write:

myStack.push(value);

The difference is the required level of isolation. In C, the stackPush procedure could be in the

same source file as the rest of the program and if it was, any other pieces of the program in

that source file could see and modify all of the low level details of how the stack was

implemented, completely bypassing the intended interface. In C++, regardless of where the

class is placed, only the methods which are part of myStack will be able to get access to those

low-level details without going through the formal interface methods. Languages such as C

can provide comparable levels of protection by using different source files and not providing

external linkage to the private parts of the stack implementation.

3. Some recommended usages

A public method should preserve the class invariants of the object it is associated with, and

should always assume that they are valid when it commences execution (private methods do

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

38www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 39: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

not necessarily need to follow this recommendation). To this effect, preconditions are used to

constrain the method's parameters, and postconditions to constrain method's output, if it has

one. If any one of either the preconditions or postconditions is not met, a method may raise

an exception. If the object's state does not satisfy its class invariants on entry to or exit from

any method, the program is considered to have a bug.

The difference between a procedure and a method is that the latter, being associated with a

particular object, may access or modify the data private to that object in a way consistent with

the intended behavior of the object. Consequently, rather than thinking "a method is just a

sequence of commands", a programmer using an object-oriented language will consider a

method to be "an object's way of providing a service" (its "method of doing the job", hence

the name); a method call is thus considered to be a request to an object to perform some task.

Consequently, method calls are often modeled as a means of passing a message to an object.

Rather than directly performing an operation on an object, a message (most of the time

accompanied by parameters) is sent to the object telling it what it should do. The object either

complies or raises an exception describing why it cannot do so. Applied to our stack example,

rather than pushing a value onto the stack, a value is sent to the stack, along with the message

"push".

4. Virtual inheritance

In the C++ programming language, virtual inheritance is a kind of inheritance that solves

some of the problems caused by multiple inheritance (particularly the "diamond problem") by

clarifying ambiguity over which ancestor class members to use. It is used when inheritance is

representing restrictions of a set rather than composition of parts. A multiply-inherited base

class is denoted as virtual with the virtual keyword.

Now the Animal portion of Bat::WingedAnimal is the same Animal as the one used by

Bat::Mammal, which is to say that a Bat has only one Animal in its representation and so a

call to Bat::eat() is unambiguous.

This is implemented by providing Mammal and WingedAnimal with a vtable pointer since,

e.g., the memory offset between the beginning of a Mammal and of its Animal part is

unknown until runtime. Thus Bat becomes

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

39www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 40: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

(vtable*,Mammal,vtable*,WingedAnimal,Bat,Animal). Two vtable pointers per object, so the

object size increased by two pointers, but now there is only one Animal and no ambiguity.

There are two vtables pointers: one per inheritance hierarchy that virtually inherits Animal:

One for Mammal and one for WingedAnimal. All objects of type Bat will have the same

vtable *'s, but each Bat object will contain its own unique Animal object. If another class

inherits Mammal, such as Squirrel, then the vtable* in the Mammal object in a Squirrel will

be different from the vtable* in the Mammal object in a Bat, although they can still be

essentially the same in the special case that the squirrel part of the object has the same size as

the Bat part, because then the distance from the Mammal to the Animal part is the same. The

vtables are not really the same, but all essential information in them (the distance) is.

Topic : Arrays

Topic Objective:

At the end of this topic the student will be able to understand:

Arrays

Properties of Arrays

Applications of Arrays

Indexing of Arrays

Multi-dimensional arrays

Definition/Overview:

Overview: In computer science, an array is a data structure consisting of a group of elements

that are accessed by indexing. In most programming languages each element has the same

data type and the array occupies a contiguous area of storage.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

40www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 41: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Key Points:

1. Arrays

Most programming languages have a built-in array data type, although what is called an array

in the language documentation is sometimes really an associative array. Conversely, the

contiguous storage kind of array discussed here may alternatively be called a vector, list, or

table.

Some programming languages support array programming (e.g., APL, newer versions of

Fortran) which generalizes operations and functions to work transparently over arrays as they

do with scalars, instead of requiring looping over array members.

Multi-dimensional arrays are accessed using more than one index: one for each dimension.

Multidimensional indexing reduced to a lesser number of dimensions, for example, a two-

dimensional array with consisting of 6 and 5 elements respectively could be represented

using a one-dimensional array of 30 elements.

Arrays can be classified as fixed-sized arrays (sometimes known as static arrays) whose size

cannot change once their storage has been allocated, or dynamic arrays, which can be resized.

2. Properties

Arrays permit constant time (O(1)) random access to individual elements, which is optimal,

but moving elements requires time proportional to the number of elements moved. On actual

hardware, the presence of e.g. caches can make sequential iteration over an array noticeably

faster than random access a consequence of arrays having good locality of reference because

their elements occupy contiguous memory locations but this does not change the asymptotic

complexity of access. Likewise, there are often facilities (such as memcpy) which can be

used to move contiguous blocks of array elements faster than one can do through individual

element access, but that does not change the asymptotic complexity either.

Memory-wise, arrays are compact data structures with no per-element overhead. There may

be a per-array overhead, e.g. to store index bounds, but this is language-dependent. It can also

happen that elements stored in an array require less memory than the same elements stored in

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

41www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 42: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

individual variables, because several array elements can be stored in a single word; such

arrays are often called packed arrays.

2.1 Properties in comparison

Dynamic arrays have similar characteristics to arrays, but can grow. The price for this

is a memory overhead, due to elements being allocated but not used. With a constant

per-element bound on the memory overhead, dynamic arrays can grow in constant

amortized time per element.

Associative arrays provide a mechanism for array-like functionality without huge

storage overheads when the index values are sparse. Specialized associative arrays

with integer keys include Patricia tries and Judy arrays.

Balanced trees require O(log n) time for index access, but also permit inserting or

deleting elements in Θ(log n) time. Arrays require O(n) time for insertion and deletion

of elements.

3. Applications

Arrays are used to implement mathematical vectors and matrices, as well as other kinds of

rectangular tables. In early programming languages, these were often the applications that

motivated having arrays. Because of their performance characteristics, arrays are used to

implement other data structures, such as heaps, hash tables, deques, queues, stacks, strings,

and VLists.

One or more large arrays are sometimes used to emulate in-program dynamic memory

allocation, particularly memory pool allocation. Historically, this has sometimes been the

only way to allocate "dynamic memory" portably. Array accesses with statically predictable

access patterns are a major source of data parallelism. Some algorithms store a variable

number of elements in part of a fixed-size array, which is equivalent to using dynamic array

with a fixed capacity; the so-called Pascal strings are examples of this.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

42www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 43: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

4. Indexing

The valid index values of each dimension of an array are a bounded set of integers (or values

of some enumerated type). Programming environments that check indexes for validity are

said to perform bounds checking.

4.1 Index of the first element

The index of the first element (sometimes called the "origin") varies by language.

There are three main implementations: zero-based, one-based, and n-based arrays, for

which the first element has an index of zero, one, or a programmer-specified value.

The zero-based array is more natural in the root machine language and was

popularized by the C programming language, where the abstraction of array is very

weak, and an index n of a one-dimensional array is simply the offset of the element

accessed from the address of the first (or "zeroth") element (scaled by the size of the

element). One-based arrays are based on traditional mathematics notation for matrices

and most, but not all, mathematical sequences. n-based is made available so the

programmer is free to choose the lower bound, which may even be negative, which is

most naturally suited for the problem at hand. The Comparison of programming

languages (array), indicates the base index used by various languages.

Supporters of zero-based indexing sometimes criticize one-based and n-based arrays

for being slower. Often this criticism is mistaken when one-based or n-based array

accesses are optimized with common subexpression elimination (for single

dimensioned arrays) and/or with well-defined dope vectors (for multi-dimensioned

arrays). However, in multidimensional arrays where the net offset into linear memory

is computed from all of the indices, zero-based indexing is more natural, simpler, and

faster. Edsger W. Dijkstra expressed an opinion in this debate: Why numbering

should start at zero.

The 0-based/1-based debate is not limited to just programming languages. For

example, the ground-floor of a building is elevator button "0" in France, but elevator

button "1" in the USA.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

43www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 44: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

4.2 Index of the last element

The relation between numbers appearing in an array declaration and the index of that

array's last element also varies by language. In some languages (e.g. C) the number of

elements contained in the arrays must be specified, whereas in others (e.g. Visual

Basic .NET) the numeric value of the index of the last element must be specified.

4.3 Indexing methods

When an array is implemented as continuous storage, the index-based access, e.g. to

element n, is simply done (for zero-based indexing) by using the address of the first

element and adding n sizeof(one element). So this is a Θ(1) operation.

5. Multi-dimensional arrays

Ordinary arrays are indexed by a single integer. Also useful, particularly in numerical and

graphics applications, is the concept of a multi-dimensional array, in which we index into the

array using an ordered list of integers, such as in a. The number of integers in the list used to

index into the multi-dimensional array is always the same and is referred to as the array's

dimensionality, and the bounds on each of these are called the array's dimensions. An array

with dimensionality k is often called k-dimensional. One-dimensional arrays correspond to

the simple arrays discussed thus far; two-dimensional arrays are a particularly common

representation for matrices. In practice, the dimensionality of an array rarely exceeds three.

Mapping a one-dimensional array into memory is obvious, since memory is logically itself a

(very large) one-dimensional array. When we reach higher-dimensional arrays, however, the

problem is no longer obvious. Suppose we want to represent this simple two-dimensional

array:

Row-major order. Used most notably by statically-declared arrays in C. The elements of each

row are stored in order.

1 2 3 4 5 6 7 8 9

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

44www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 45: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Column-major order. Used most notably in FORTRAN. The elements of each column are

stored in order.

1 4 7 2 5 8 3 6 9

Arrays of arrays. Multi-dimensional arrays are typically represented by one-dimensional

arrays of references (Iliffe vectors) to other one-dimensional arrays. The subarrays can be

either the rows or columns.

The first two forms are more compact and have potentially better locality of reference, but are

also more limiting; the arrays must be rectangular, meaning that no row can contain more

elements than any other. Arrays of arrays, on the other hand, allow the creation of ragged

arrays, also called jagged arrays, in which the valid range of one index depends on the value

of another, or in this case, simply that different rows can be different sizes. Arrays of arrays

are also of value in programming languages that only supply one-dimensional arrays as

primitives.

In many applications, such as numerical applications working with matrices, we iterate over

rectangular two-dimensional arrays in predictable ways. For example, computing an element

of the matrix product AB involves iterating over a row of A and a column of B

simultaneously. In mapping the individual array indexes into memory, we wish to exploit

locality of reference as much as we can. A compiler can sometimes automatically choose the

layout for an array so that sequentially accessed elements are stored sequentially in memory;

in our example, it might choose row-major order for A, and column-major order for B. Even

more exotic orderings can be used, for example if we iterate over the main diagonal of a

matrix.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

45www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 46: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Topic : Objects And Classes

Topic Objective:

At the end of this topic the student will be able to understand:

Reasons for using classes

Instantiation

Interfaces and methods

Structure of a class

Information hiding and encapsulation

Associations between classes

Definition/Overview:

Overview: In object-oriented programming, a class is a programming language construct that

is used as a blueprint to create objects. This blueprint includes attributes and methods that the

created objects all share. Usually, a class represents a person, place, or thing - it is an

abstraction of a concept within a computer program. Fundamentally, it encapsulates the state

and behavior of that which it conceptually represents. It encapsulates state through data

placeholders called member variables; it encapsulates behavior through reusable code called

methods. More technically, a class is a cohesive package that consists of a particular kind of

metadata. It describes the rules by which objects behave; these objects are referred to as

instances of that class. A class has both an interface and a structure. The interface describes

how the class and its instances can be interacted with via methods, while the structure

describes how the data is partitioned into attributes within an instance. A class may also have

a representation (metaobject) at runtime, which provides runtime support for manipulating

the class-related metadata. In object-oriented design, a class is the most specific type of an

object in relation to a specific layer. Programming languages that support classes all subtly

differ in their support for various class-related features. Most support various forms of class

inheritance. Many languages also support features providing encapsulation, such as access

specifiers.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

46www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 47: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Key Points:

1. Reasons for using classes

Classes, when used properly, can accelerate development by reducing redundant code entry,

testing and bug fixing. If a class has been thoroughly tested and is known to be a solid work,

it is typically the case that using or extending the well-tested class will reduce the number of

bugs - as compared to the use of freshly-developed or ad hoc code - in the final output. In

addition, efficient class reuse means that many bugs need be fixed in only one place when

problems are discovered.

Another reason for using classes is to simplify the relationships of interrelated data. Rather

than writing code to repeatedly call a GUI window drawing subroutine on the terminal screen

(as would be typical for structured programming), it is more intuitive to represent the window

as an object and tell it to draw itself as necessary. With classes, GUI items that are similar to

windows (such as dialog boxes) can simply inherit most of their functionality and data

structures from the window class. The programmer then need only add code to the dialog

class that is unique to its operation. Indeed, GUIs are a very common and useful application

of classes, and GUI programming is generally much easier with a good class framework.

2. Instantiation

A class is used to create new instances (objects) by instantiating the class. Instances of a class

share the same set of attributes, yet may differ in what those attributes contain. For example,

a class "Person" would describe the attributes common to all instances of the Person class.

Each person is generally alike, but varies in such attributes as "height" and "weight". The

class would list types of such attributes and also define the actions which a person can

perform: "run", "jump", "sleep", "walk", etc. One of the benefits of programming with classes

is that all instances of a particular class will follow the defined behavior of the class they

instantiate.

In most languages, the structures as defined by the class determine how the memory used by

its instances will be laid out. This technique is known as the cookie-cutter model. The

alternative to the cookie-cutter model is the model of Python, wherein objects are structured

as associative key-value containers. In such models, objects that are instances of the same

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

47www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 48: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

class could contain different instance variables, as state can be dynamically added to the

object. This may resemble prototype-based languages in some ways, but it is not equivalent.

In strictly mathematical branches of computer science the term object is used in a purely

mathematical sense to refer to any thing. While this interpretation is useful in the discussion

of abstract theory, it is not concrete enough to serve as a primitive data type in the discussion

of more concrete branches (such as programming) that are closer to actual computation and

information processing. Therefore, objects are still conceptual entities, but generally

correspond directly to a contiguous block of computer memory of a specific size at a specific

location. This is because computation and information processing ultimately require a form

of computer memory. Objects in this sense are fundamental primitives needed to accurately

define concepts such as references, variables, and name binding. This is why the rest of this

article will focus on the concrete interpretation of an object rather than the abstract one object

oriented programming.

Note that although a block of computer memory can appear contiguous on one level of

abstraction and incontiguous on another, the important thing is that it appears contiguous to

the program that treats it as an object. That is, an object's private implementation details must

not be exposed to clients of the object, and they must be able to change without requiring

changes to client code. In particular, the size of the block of memory that forms the object

must be able to change without changes to client code.

Objects exist only within contexts that are aware of them; a piece of computer memory only

holds an object if a program treats it as such (for example by reserving it for exclusive use by

specific procedures and/or associating a data type with it). Thus, the lifetime of an object is

the time during which it is treated as an object. This is why they are still conceptual entities,

despite their physical presence in computer memory.

In other words, abstract concepts that do not occupy memory space at runtime are, according

to the definition, not objects; e.g., design patterns exhibited by a set of classes, data types in

statically typed programs.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

48www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 49: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

3. Interfaces and methods

Objects define their interaction with the outside world through the methods that they expose.

A method, or instance method, is a subroutine (function) with a special property that it has

access to data stored in an object (instance). Methods that manipulate the data of the object

and perform tasks are sometimes described as behavior.

Methods form the object's interface with the outside world; the buttons on the front of your

television set, for example, are the interface between you and the electrical wiring on the

other side of its plastic casing. You press the "power" button to toggle the television on and

off. In this example, the television is the instance, each method is represented by a button,

and all the buttons together comprise the interface. In its most common form, an interface is a

specification of a group of related methods without any associated implementation of the

methods.

Every class implements (or realizes) an interface by providing structure (i.e. data and state)

and method implementations (i.e. providing code that specifies how methods work). There is

a distinction between the definition of an interface and the implementation of that interface.

In most languages, this line is usually blurred, because a class declaration both defines and

implements an interface. Some languages, however, provide features that help separate

interface and implementation. For example, an abstract class can define an interface without

providing implementation, and in the Dylan language, class definitions do not even define

interfaces.

Interfaces may also be defined to include a set of auxiliary functions called static methods or

class methods. Static methods, like instance methods, are exclusively associated with the

class. They differ from instance methods in that they do not work with instances of the class;

that is, static methods neither require an instance of the class nor can they access the data of

such an instance. For example, getting the total number of televisions in existence could be a

static method of the television class. This method is clearly associated with the class, yet is

outside the domain of each individual instance of the class. Another example is a static

method that finds a particular instance out of the set of all television sets.

Languages that support class inheritance also allow classes to inherit interfaces from the

classes that they are derived from. In languages that support access specifiers, the interface of

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

49www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 50: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

a class is considered to be the set of public members of the class, including both methods and

attributes (via implicit getter and setter methods); any private members or internal data

structures are not intended to be depended on by client code and thus are not part of the

interface.

The object-oriented programming methodology is designed in such a way that the operations

of any interface of a class are usually chosen to be independent of each other. It results in a

client-server (or layered) design where servers do not depend in any way on the clients. An

interface places no requirements for clients to invoke the operations of one interface in any

particular order. This approach has the benefit that client code can assume that the operations

of an interface are available for use whenever the client holds a valid reference to the object.

4. Structure of a class

Along with having an interface, a class contains a description of structure of data stored in the

instances of the class. The data is partitioned into attributes (or properties, fields, data

members). Going back to the television set example, the myriad attributes, such as size and

whether it supports color, together comprise its structure. A class represents the full

description of a television, including its attributes (structure) and buttons (interface).

The state of an instance's data is stored in some resource, such as memory or a file. The

storage is assumed to be located in a specific location, such that it is possible to access the

instance through references to the identity of the instances. However, the actual storage

location associated with an instance may change with time. In such situations, the identity of

the object does not change. The state is encapsulated and every access to the state occurs

through methods of the class.

A class also describes a set of invariants that are preserved by every method in the class. An

invariant is a constraint on the state of an object that should be satisfied by every object of the

class. The main purpose of the invariants is to establish what objects belong to the class. An

invariant is what distinguishes data types and classes from each other; that is, a class does not

allow use of all possible values for the state of the object, and instead allows only those

values that are well-defined by the semantics of the intended use of the data type. The set of

supported (public) methods often implicitly establishes an invariant. Some programming

languages support specification of invariants as part of the definition of the class, and enforce

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

50www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 51: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

them through the type system. Encapsulation of state is necessary for being able to enforce

the invariants of the class.

Some languages allow an implementation of a class to specify constructor (or initializer) and

destructor (or finalizer) methods that specify how instances of the class are created and

destroyed, respectively. A constructor that takes arguments can be used to create an instance

from passed-in data. The main purpose of a constructor is to establish the invariant of the

class, failing if the invariant isn't valid. The main purpose of a destructor is to destroy the

identity of the instance, invalidating any references in the process. Constructors and

destructors are often used to reserve and release, respectively, resources associated with the

object. In some languages, a destructor can return a value which can then be used to obtain a

public representation (transfer encoding) of an instance of a class and simultaneously destroy

the copy of the instance stored in current thread's memory.

A class may also contain static attributes or class attributes, which contain data that are

specific to the class yet are common to all instances of the class. If the class itself is treated as

an instance of a hypothetical metaclass, static attributes and static methods would be instance

attributes and instance methods of that metaclass.

4.1 Run-time representation of classes

As a data type, a class is usually considered as a compile-time construct. A language

may also support prototype or factory metaobjects that represent run-time information

about classes, or even represent metadata that provides access to reflection facilities

and ability to manipulate data structure formats at run-time. Many languages

distinguish this kind of run-time type information about classes from a class on the

basis that the information is not needed at run-time. Some dynamic languages do not

make strict distinctions between run-time and compile-time constructs, and therefore

may not distinguish between metaobjects and classes.

For example: if Human is a metaobject representing the class Person, then instances

of class Person can be created by using the facilities of the Human metaobject.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

51www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 52: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

5. Information hiding and encapsulation

Many languages support the concept of information hiding and encapsulation, typically with

access specifiers for class members. Access specifiers specify constraints on who can access

which class members. Some access specifiers may also control how classes inherit such

constraints. Their primary purpose is to separate the interface of a class with its

implementation.

A common usage of access specifiers is to separate the internal data structures of a class from

its interface; that is, the internal data structures are private. Public accessor methods can be

used to inspect or alter such private data. The various object-oriented programming languages

enforce this to various degrees. For example, the Java language does not allow client code to

access the private data of a class at all, whereas in languages like Objective-C or Perl client

code can do whatever it wants. In C++ language, private methods are visible but not

accessible in the interface; however, they are commonly made invisible by explicitly

declaring fully abstract classes that represent the interfaces of the class.

Access specifiers do not necessarily control visibility, in that even private members may be

visible to client code. In some languages, an inaccessible but visible member may be referred

to at run-time (e.g. pointer to it can be returned from member functions), but all attempts to

use it by referring to the name of the member from client code will be prevented by the type

checker. Object-oriented design uses the access specifiers in conjunction with careful design

of public method implementations to enforce class invariants. Access specifiers are intended

to protect against accidental use of members by clients, but are not suitable for run-time

protection of object's data.

Some languages, such as Ruby, support instance-private and instance-protected access

specifiers in lieu of (or in addition to) class-private and class-protected, respectively. They

differ in that they restrict access based on the instance itself, rather than the instance's class.

In addition, some languages, such as C++, support a mechanism where a function explicitly

declared as friend of the class may access the members designated as private or protected.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

52www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 53: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

6. Associations between classes

In object-oriented design and in UML, an association between two classes is a type of a link

between the corresponding objects. A (two-way) association between classes A and B

describes a relationship between each object of class A and some objects of class B, and vice

versa. Associations are often named with a verb, such as "subscribes-to".

An association role type describes the role type of an instance of a class when the instance

participates in an association. An association role type is related to each end of the

association. A role describes an instance of a class from the point of view of a situation in

which the instance participates in the association. Role types are collections of role

(instance)s grouped by their similar properties. For example, a "subscriber" role type

describes the property common to instances of the class "Person" when they participate in a

"subscribes-to" relationship with the class "Magazine". Also, a "Magazine" has the

"subscribed magazine" role type when the subscribers subscribe-to it.

Association role multiplicity describes how many instances correspond to each instance of

the other class(es) of the association. Common multiplicities are "0..1", "1..1", "1..*" and

"0..*", where the "*" specifies any number of instances. There are some special kinds of

associations between classes.

6.1Composition

Composition between class A and class B describes a has-a relationship where

instances of class B have shorter or same lifetime than the lifetime of the

corresponding instances of the enclosing class. Class B is said to be a part of class A.

This is often implemented in programming languages by allocating the data storage of

instances of class A to contain a representation of instances of class B.

Aggregation is a variation of composition that describes that instances of a class are

part of instances of the other class, but the constraint on lifetime of the instances is not

required. The implementation of aggregation is often via a pointer or reference to the

contained instance. In both cases, method implementations of the enclosing class can

invoke methods of the part class. A common example of aggregation is a list class.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

53www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 54: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

When a list's lifetime is over, it does not necessarily mean the lifetimes of the objects

within the list are also over.

6.2 Inheritance

Another type of class association is inheritance, which involves subclasses and

superclasses, also known respectively as child classes (or derived classes) and parent

classes (or base classes). If [car] was a class, then [station wagon] and [mini-van]

might be two subclasses. If [Button] is a subclass of [Control], then all buttons are

controls. In other words, inheritance is an is-a relationship between two classes.

Subclasses usually consist of several kinds of modifications (customizations) to their

respective superclasses: addition of new instance variables, addition of new methods

and overriding of existing methods to support the new instance variables.

Conceptually, a superclass should be considered as a common part of its subclasses.

This factoring of commonality is one mechanism for providing reuse. Thus, extending

a superclass by modifying the existing class is also likely to narrow its applicability in

various situations. In object-oriented design, careful balance between applicability

and functionality of superclasses should be considered. Subclassing is different from

subtyping in that subtyping deals with common behaviour whereas subclassing is

concerned with common structure.

Some programming languages (for example C++) allow multiple inheritance - they

allow a child class to have more than one parent class. This technique has been

criticized by some for its unnecessary complexity and being difficult to implement

efficiently, though some projects have certainly benefited from its use. Java, for

example has no multiple inheritance, as its designers felt that it would add

unnecessary complexity. Java instead allows inheriting from multiple pure abstract

classes (called interfaces in Java).

Sub- and superclasses are considered to exist within a hierarchy defined by the

inheritance relationship. If multiple inheritance is allowed, this hierarchy is a directed

acyclic graph (or DAG for short), otherwise it is a tree. The hierarchy has classes as

nodes and inheritance relationships as links. The levels of this hierarchy are called

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

54www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 55: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

layers or levels of abstraction. Classes in the same level are more likely to be

associated than classes in different levels.

There are two slightly different points of view as to whether subclasses of the same

class are required to be disjoint. Sometimes, subclasses of a particular class are

considered to be completely disjoint. That is, every instance of a class has exactly one

most-derived class, which is a subclass of every class that the instance has. This view

does not allow dynamic change of object's class, as objects are assumed to be created

with a fixed most-derived class. The basis for not allowing changes to object's class is

that the class is a compile-time type, which does not usually change at runtime, and

polymorphism is utilized for any dynamic change to the object's behavior, so this

ability is not necessary. And design that does not need to perform changes to object's

type will be more robust and easy-to-use from the point of view of the users of the

class.

From another point of view, subclasses are not required to be disjoint. Then there is

no concept of a most-derived class, and all types in the inheritance hierarchy that are

types of the instance are considered to be equally types of the instance. This view is

based on a dynamic classification of objects, such that an object may change its class

at runtime. Then object's class is considered to be its current structure, but changes to

it are allowed. The basis for allowing changes to object's class is a perceived

inconvenience caused by replacing an instance with another instance of a different

type, since this would require change of all references to the original instance to be

changed to refer to the new instance. When changing the object's class, references to

the existing instances do not need to be replaced with references to new instances

when the class of the object changes. However, this ability is not readily available in

all programming languages. This analysis depends on the proposition that dynamic

changes to object structure are common. This may or may not be the case in practice.

6.3 Languages without inheritance

Although class-based languages are commonly assumed to support inheritance,

inheritance is not an intrinsic aspect of the concept of classes. There are languages

that support classes yet do not support inheritance. Examples are earlier versions of

Visual Basic. These languages, sometimes called "object-based languages", do not

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

55www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 56: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

provide the structural benefits of statically type-checked interfaces for objects. This is

because in object-based languages, it is possible to use and extend data structures and

attach methods to them at run-time. This precludes the compiler or interpreter from

being able to check the type information specified in the source code as the type is

built dynamically and not defined statically. Most of these languages allow for

instance behaviour and complex operational polymorphism (see dynamic dispatch and

polymorphism).

In Section 2 of this course you will cover these topics:Strings And Text I/O

Inheritance And Polymorphism

Abstract Classes And Interfaces

Object-Oriented Design

Gui Basics

Graphics

Event-Driven Programming

Topic : Strings And Text I/O

Topic Objective:

At the end of this topic the student will be able to understand:

String data types

Text Input/output

Definition/Overview:

Definition: In computer programming and some branches of mathematics, a string is an

ordered sequence of symbols. These symbols are chosen from a predetermined set or

alphabet. In computer programming, a string is generally understood as a data type storing a

sequence of data values, usually bytes, in which elements usually stand for characters

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

56www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 57: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

according to a character encoding, which differentiates it from the more general array data

type. In this context, the terms binary string and byte string are used to suggest strings in

which the stored data does not (necessarily) represent text. A variable declared to have a

string data type usually causes storage to be allocated in memory that is capable of holding

some predetermined number of symbols. When a string appears literally in source code, it is

known as a string literal and has a representation that denotes it as such.

In computing, input/output, or I/O, refers to the communication between an information

processing system (such as a computer), and the outside world possibly a human, or another

information processing system. Inputs are the signals or data received by the system, and

outputs are the signals or data sent from it. The term can also be used as part of an action; to

"perform I/O" is to perform an input or output operation. I/O devices are used by a person (or

other system) to communicate with a computer. For instance, keyboards and mouses are

considered input devices of a computer, while monitors and printers are considered output

devices of a computer. Devices for communication between computers, such as modems and

network cards, typically serve for both input and output..

Key Points:

1. String data types

A string data type is a data type modeled on the idea of a formal string. Strings are such an

important and useful data type that they are implemented in nearly every programming

language. In some languages they are available as primitive types and in others as composite

types. The syntax of most high-level programming languages allows for a string, usually

quoted in some way, to represent an instance of a string data type; such a meta-string is called

a literal or string literal.

Although formal strings can have an arbitrary (but finite) length, the length of strings in real

languages is often constrained to an artificial maximum. In general, there are two types of

string data types: fixed length strings which have a fixed maximum length and which use the

same amount of memory whether this maximum is reached or not, and variable length strings

whose length is not arbitrarily fixed and which use varying amounts of memory depending on

their actual size. Most strings in modern programming languages are variable length strings.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

57www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 58: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Despite the name, even variable length strings are limited in length; although, generally, the

limit depends only on the amount of memory available.

Historically, string data types allocated one byte per character, and although the exact

character set varied by region, character encodings were similar enough that programmers

could generally get away with ignoring this groups of character sets used by the same system

in different regions usually either had a character in the same place, or did not have it at all.

These character sets were typically based on ASCII or EBCDIC.

Logographic languages such as Chinese, Japanese, and Korean (known collectively as CJK)

need far more than 256 characters (the limit of a one 8-bit byte per-character encoding) for

reasonable representation. The normal solutions involved keeping single-byte representations

for ASCII and using two-byte representations for CJK ideographs. Use of these with existing

code led to problems with matching and cutting of strings, the severity of which depended on

how the character encoding was designed. Some encodings such as the EUC family guarantee

that a byte value in the ASCII range will only represent that ASCII character, making the

encoding safe for systems that use those characters as field separators. Other encodings such

as ISO-2022 and Shift-JIS do not make such guarantees, making matching on byte codes

unsafe. Another issue is that if the beginning of a string is deleted, important instructions for

the decoder or information on position in a multibyte sequence may be lost. Another is that if

strings are joined together (especially after having their ends truncated by code not aware of

the encoding), the first string may not leave the encoder in a state suitable for dealing with the

second string.

Unicode has simplified the picture somewhat. Most languages have a data type for Unicode

strings (usually UTF-16 as it was usually added before Unicode supplemental planes were

introduced). Converting between Unicode and local encodings requires an understanding of

the local encoding, which may be problematic for existing systems where strings of various

encodings are being transmitted together with no real marking as to what encoding they are

in.

Some languages like C++ implement strings as templates that can be used with any data type,

but this is the exception, not the rule. If an object-oriented language represents strings as

objects, they are called mutable if the value can change at runtime and immutable if the value

is frozen after creation. For example, Ruby has mutable strings, while Python's strings are

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

58www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 59: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

immutable. Other languages, most notably Prolog and Erlang, avoid implementing a string

data type, instead adopting the convention of representing strings as lists of character codes.

2. Text Input/output

In computer architecture, the combination of the CPU and main memory (i.e. memory that

the CPU can read and write to directly, with individual instructions) is considered the brain of

a computer, and from that point of view any transfer of information from or to that

combination, for example to or from a disk drive, is considered I/O. The CPU and its

supporting circuitry provide memory-mapped I/O that is used in low-level computer

programming in the implementation of device drivers.

Higher-level operating system and programming facilities employ separate, more abstract I/O

concepts and primitives. For example, most operating systems provide application programs

with the concept of files. The C and C++ programming languages, and operating systems in

the Unix family, traditionally abstract files and devices as streams, which can be read or

written, or sometimes both. The C standard library provides functions for manipulating

streams for input and output.

Transput - In the context of the ALGOL 68 programming language, the input and output

facilities are collectively referred to as transput. The ALGOL 68 transput library recognizes

the following standard files/devices: stand in, stand out, stand error and stand back.

An alternative to special primitive functions is the I/O monad, which permits programs to just

describe I/O, and the actions are carried out outside the program. This is notable because the

I/O functions would introduce side-effects to any programming language, but now purely

functional programming is practical.

Topic : Inheritance And Polymorphism

Topic Objective:

At the end of this topic the student will be able to understand:

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

59www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 60: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Inheritance with Polymorphism

Parametric Polymorphism

Operator Overloading

Definition/Overview:

Overview: In simple terms, polymorphism is the ability of one type, A, to appear as and be

used like another type, B. In strongly typed languages, this usually means that type A

somehow derives from type B, or type A implements an interface that represents type B.

In non-strongly typed languages (dynamically typed languages) types are implicitly

polymorphic to the extent they have similar features (fields, methods, operators). In fact, this

is one of the principal benefits (and pitfalls) of dynamic typing.

Operator Overloading the numerical operators +,-,/,* allow polymorphic treatment of the

various numerical types Integer, UnSigned Integer, Float, Decimal, etc; each of which have

different ranges, bit patterns, and representations. Another common example is the use of the

"+" operator which allows similar or polymorphic treatment of numbers (addition), strings

(concatenation), and lists (attachment). This is a lesser used feature of polymorphism.

The primary usage of polymorphism in industry (object-oriented programming theory) is the

ability of objects belonging to different types to respond to method, field, or property calls of

the same name, each one according to an appropriate type-specific behavior. The programmer

(and the program) does not have to know the exact type of the object in advance, and so the

exact behavior is determined at run time (this is called late binding or dynamic binding).

The different objects involved only need to present a compatible interface to the clients (the

calling routines). That is, there must be public or internal methods, fields, events, and

properties with the same name and the same parameter sets in all the Superclasses,

Subclasses, and potentially Interfaces. In principle, the object types may be unrelated, but

since they share a common interface, they are often implemented as Subclasses of the same

Superclass. Though it is not required, it is understood that the different methods will also

produce similar results (for example, returning values of the same type).

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

60www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 61: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Key Points:

1. Inheritance with Polymorphism

If a Dog is commanded to speak(), she may emit a bark, while if a Pig is asked to speak(), he

may respond with an oink. Both inherit speak() from Animal, but their subclass methods

override the methods of the superclass, known as overriding polymorphism. Adding a walk

class to Animal would give both Pig and Dog object's the same walk method.

Inheritance combined with polymorphism allows class B to inherit from class A without

having to retain all features of class A; it can do some of the things that class A does

differently. This means that the same "verb" can result in different actions as appropriate for a

specific class. Calling code can issue the same command to their superclass or interface and

get appropriately different results from each one.

Dynamic language performance is hindered by the extra checks and searches that occur at

each call site. Straightforward implementations have to repeatedly search class precedence

lists for members and potentially resolve overloads on method argument types each time you

execute a particular line of code. In an expression such as o.m(x, y) or x + y, dynamic

languages need to check exactly what kind of object o is, what is m bound to for o, what type

x is, what type y is, or what "+" means for the actual runtime type of x and y. In a statically

typed language (or with enough type hints in the code and type inferencing), you can emit

exactly the instructions or runtime function calls that are appropriate at each call site. You

can do this because you know from the static types what is needed at compile time.

Dynamic languages provide great productivity enhancements and powerful terse expressions

due to their dynamic capabilities. However, in practice code tends to execute on the same

types of objects each time. This means you can improve performance by remembering the

results of method searches the first time a section of code executes. For example, with x + y,

if x and y are integers the first time that expression executes, we can remember a code

sequence or exactly what runtime function performs addition given two integers. Then each

time that expression executes, there is no search involved. The code just checks that x and y

are integers again, and dispatches to the right code with no searching. The result can literally

be reduced to inlined code generation with a couple of type checks and an add instruction,

depending on the semantics of an operation and method caching mechanisms used

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

61www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 62: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

2. Parametric Polymorphism

In object-oriented programming languages, the term polymorphism has different, but related

meanings; one of these, parametric polymorphism, is known as generic programming in the

Object Oriented Programming Community and is supported by many languages including

C++, C# and Java.

Generics allow you compile time type safety and other benefits and/or disadvantages

depending on the language's implementation.

C++ implements parametric polymorphism through templates. The use of templates requires

the compiler to generate a separate instance of the templated class or function for every

permutation of type parameters used with it, which can lead to code bloat and difficulty

debugging. A benefit C++ templates have over Java and C# is that they allow for template

metaprogramming, which is a way of pre-evaluating some of the code at compile-time rather

than run-time.

Java parametric polymorphism is called generics and implemented through type erasure.

C# parametric polymorphism is called generics and implemented by reification, making C#

the only language of the three which supports parametric polymorphism as a first class

member of the language. This design choice is leveraged to provide additional functionality,

such as allowing reflection with preservation of generic types, as well as alleviating some of

the limitations of erasure (such as being unable to create generic arrays). This also means that

there is no performance hit from runtime casts and normally expensive boxing conversions.

When primitive and value types are used as generic arguments, they get specialized

implementations, allowing for efficient generic collections and methods.

3. Operator Overloading

Overloading polymorphism is the use of one method signature or operator (such as "+") to

perform several different functions depending on the implementation. The "+" operator, for

example, may be used to perform integer addition, float addition, string concatenation, or list

concatenation, allowing Integer and Double, both subclasses of Number, to add together

properly in OOP languages.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

62www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 63: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Topic : Abstract Classes And Interfaces

Topic Objective:

At the end of this topic the student will be able to understand:

Reasons for using classes

Instantiation

Interfaces and methods

Structure of a class

Information hiding and encapsulation

Associations between classes

Definition/Overview:

Overview: In object-oriented programming, a class is a programming language construct that

is used as a blueprint to create objects. This blueprint includes attributes and methods that the

created objects all share. Usually, a class represents a person, place, or thing - it is an

abstraction of a concept within a computer program. Fundamentally, it encapsulates the state

and behavior of that which it conceptually represents. It encapsulates state through data

placeholders called member variables; it encapsulates behavior through reusable code called

methods. More technically, a class is a cohesive package that consists of a particular kind of

metadata. It describes the rules by which objects behave; these objects are referred to as

instances of that class. A class has both an interface and a structure. The interface describes

how the class and its instances can be interacted with via methods, while the structure

describes how the data is partitioned into attributes within an instance. A class may also have

a representation (metaobject) at runtime, which provides runtime support for manipulating

the class-related metadata. In object-oriented design, a class is the most specific type of an

object in relation to a specific layer. Programming languages that support classes all subtly

differ in their support for various class-related features. Most support various forms of class

inheritance. Many languages also support features providing encapsulation, such as access

specifiers.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

63www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 64: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Key Points:

1. Reasons for using classes

Classes, when used properly, can accelerate development by reducing redundant code entry,

testing and bug fixing. If a class has been thoroughly tested and is known to be a solid work,

it is typically the case that using or extending the well-tested class will reduce the number of

bugs - as compared to the use of freshly-developed or ad hoc code - in the final output. In

addition, efficient class reuse means that many bugs need be fixed in only one place when

problems are discovered.

Another reason for using classes is to simplify the relationships of interrelated data. Rather

than writing code to repeatedly call a GUI window drawing subroutine on the terminal screen

(as would be typical for structured programming), it is more intuitive to represent the window

as an object and tell it to draw itself as necessary. With classes, GUI items that are similar to

windows (such as dialog boxes) can simply inherit most of their functionality and data

structures from the window class. The programmer then need only add code to the dialog

class that is unique to its operation. Indeed, GUIs are a very common and useful application

of classes, and GUI programming is generally much easier with a good class framework.

2. Instantiation

A class is used to create new instances (objects) by instantiating the class. Instances of a class

share the same set of attributes, yet may differ in what those attributes contain. For example,

a class "Person" would describe the attributes common to all instances of the Person class.

Each person is generally alike, but varies in such attributes as "height" and "weight". The

class would list types of such attributes and also define the actions which a person can

perform: "run", "jump", "sleep", "walk", etc. One of the benefits of programming with classes

is that all instances of a particular class will follow the defined behavior of the class they

instantiate.

In most languages, the structures as defined by the class determine how the memory used by

its instances will be laid out. This technique is known as the cookie-cutter model. The

alternative to the cookie-cutter model is the model of Python, wherein objects are structured

as associative key-value containers. In such models, objects that are instances of the same

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

64www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 65: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

class could contain different instance variables, as state can be dynamically added to the

object. This may resemble prototype-based languages in some ways, but it is not equivalent.

In strictly mathematical branches of computer science the term object is used in a purely

mathematical sense to refer to any thing. While this interpretation is useful in the discussion

of abstract theory, it is not concrete enough to serve as a primitive data type in the discussion

of more concrete branches (such as programming) that are closer to actual computation and

information processing. Therefore, objects are still conceptual entities, but generally

correspond directly to a contiguous block of computer memory of a specific size at a specific

location. This is because computation and information processing ultimately require a form

of computer memory. Objects in this sense are fundamental primitives needed to accurately

define concepts such as references, variables, and name binding. This is why the rest of this

article will focus on the concrete interpretation of object rather than the abstract one object

oriented programming.

Note that although a block of computer memory can appear contiguous on one level of

abstraction and incontiguous on another, the important thing is that it appears contiguous to

the program that treats it as an object. That is, an object's private implementation details must

not be exposed to clients of the object, and they must be able to change without requiring

changes to client code. In particular, the size of the block of memory that forms the object

must be able to change without changes to client code.

Objects exist only within contexts that are aware of them; a piece of computer memory only

holds an object if a program treats it as such (for example by reserving it for exclusive use by

specific procedures and/or associating a data type with it). Thus, the lifetime of an object is

the time during which it is treated as an object. This is why they are still conceptual entities,

despite their physical presence in computer memory.

In other words, abstract concepts that do not occupy memory space at runtime are, according

to the definition, not objects; e.g., design patterns exhibited by a set of classes, data types in

statically typed programs.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

65www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 66: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

3. Interfaces and methods

Objects define their interaction with the outside world through the methods that they expose.

A method, or instance method, is a subroutine (function) with a special property that it has

access to data stored in an object (instance). Methods that manipulate the data of the object

and perform tasks are sometimes described as behavior.

Methods form the object's interface with the outside world; the buttons on the front of your

television set, for example, are the interface between you and the electrical wiring on the

other side of its plastic casing. You press the "power" button to toggle the television on and

off. In this example, the television is the instance, each method is represented by a button,

and all the buttons together comprise the interface. In its most common form, an interface is a

specification of a group of related methods without any associated implementation of the

methods.

Every class implements (or realizes) an interface by providing structure (i.e. data and state)

and method implementations (i.e. providing code that specifies how methods work). There is

a distinction between the definition of an interface and the implementation of that interface.

In most languages, this line is usually blurred, because a class declaration both defines and

implements an interface. Some languages, however, provide features that help separate

interface and implementation. For example, an abstract class can define an interface without

providing implementation, and in the Dylan language, class definitions do not even define

interfaces.

Interfaces may also be defined to include a set of auxiliary functions called static methods or

class methods. Static methods, like instance methods, are exclusively associated with the

class. They differ from instance methods in that they do not work with instances of the class;

that is, static methods neither require an instance of the class nor can they access the data of

such an instance. For example, getting the total number of televisions in existence could be a

static method of the television class. This method is clearly associated with the class, yet is

outside the domain of each individual instance of the class. Another example is a static

method that finds a particular instance out of the set of all television sets.

Languages that support class inheritance also allow classes to inherit interfaces from the

classes that they are derived from. In languages that support access specifiers, the interface of

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

66www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 67: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

a class is considered to be the set of public members of the class, including both methods and

attributes (via implicit getter and setter methods); any private members or internal data

structures are not intended to be depended on by client code and thus are not part of the

interface.

The object-oriented programming methodology is designed in such a way that the operations

of any interface of a class are usually chosen to be independent of each other. It results in a

client-server (or layered) design where servers do not depend in any way on the clients. An

interface places no requirements for clients to invoke the operations of one interface in any

particular order. This approach has the benefit that client code can assume that the operations

of an interface are available for use whenever the client holds a valid reference to the object.

4. Structure of a class

Along with having an interface, a class contains a description of structure of data stored in the

instances of the class. The data is partitioned into attributes (or properties, fields, data

members). Going back to the television set example, the myriad attributes, such as size and

whether it supports color, together comprise its structure. A class represents the full

description of a television, including its attributes (structure) and buttons (interface).

The state of an instance's data is stored in some resource, such as memory or a file. The

storage is assumed to be located in a specific location, such that it is possible to access the

instance through references to the identity of the instances. However, the actual storage

location associated with an instance may change with time. In such situations, the identity of

the object does not change. The state is encapsulated and every access to the state occurs

through methods of the class.

A class also describes a set of invariants that are preserved by every method in the class. An

invariant is a constraint on the state of an object that should be satisfied by every object of the

class. The main purpose of the invariants is to establish what objects belong to the class. An

invariant is what distinguishes data types and classes from each other; that is, a class does not

allow use of all possible values for the state of the object, and instead allows only those

values that are well-defined by the semantics of the intended use of the data type. The set of

supported (public) methods often implicitly establishes an invariant. Some programming

languages support specification of invariants as part of the definition of the class, and enforce

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

67www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 68: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

them through the type system. Encapsulation of state is necessary for being able to enforce

the invariants of the class.

Some languages allow an implementation of a class to specify constructor (or initializer) and

destructor (or finalizer) methods that specify how instances of the class are created and

destroyed, respectively. A constructor that takes arguments can be used to create an instance

from passed-in data. The main purpose of a constructor is to establish the invariant of the

class, failing if the invariant isn't valid. The main purpose of a destructor is to destroy the

identity of the instance, invalidating any references in the process. Constructors and

destructors are often used to reserve and release, respectively, resources associated with the

object. In some languages, a destructor can return a value which can then be used to obtain a

public representation (transfer encoding) of an instance of a class and simultaneously destroy

the copy of the instance stored in current thread's memory.

A class may also contain static attributes or class attributes, which contain data that are

specific to the class yet are common to all instances of the class. If the class itself is treated as

an instance of a hypothetical metaclass, static attributes and static methods would be instance

attributes and instance methods of that metaclass.

4.1 Run-time representation of classes

As a data type, a class is usually considered as a compile-time construct. A language

may also support prototype or factory metaobjects that represent run-time information

about classes, or even represent metadata that provides access to reflection facilities

and ability to manipulate data structure formats at run-time. Many languages

distinguish this kind of run-time type information about classes from a class on the

basis that the information is not needed at run-time. Some dynamic languages do not

make strict distinctions between run-time and compile-time constructs, and therefore

may not distinguish between metaobjects and classes.

For example: if Human is a metaobject representing the class Person, then instances

of class Person can be created by using the facilities of the Human metaobject.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

68www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 69: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

5. Information hiding and encapsulation

Many languages support the concept of information hiding and encapsulation, typically with

access specifiers for class members. Access specifiers specify constraints on who can access

which class members. Some access specifiers may also control how classes inherit such

constraints. Their primary purpose is to separate the interface of a class with its

implementation.

A common usage of access specifiers is to separate the internal data structures of a class from

its interface; that is, the internal data structures are private. Public accessor methods can be

used to inspect or alter such private data. The various object-oriented programming languages

enforce this to various degrees. For example, the Java language does not allow client code to

access the private data of a class at all, whereas in languages like Objective-C or Perl client

code can do whatever it wants. In C++ language, private methods are visible but not

accessible in the interface; however, they are commonly made invisible by explicitly

declaring fully abstract classes that represent the interfaces of the class.

Access specifiers do not necessarily control visibility, in that even private members may be

visible to client code. In some languages, an inaccessible but visible member may be referred

to at run-time (e.g. pointer to it can be returned from member functions), but all attempts to

use it by referring to the name of the member from client code will be prevented by the type

checker. Object-oriented design uses the access specifiers in conjunction with careful design

of public method implementations to enforce class invariants. Access specifiers are intended

to protect against accidental use of members by clients, but are not suitable for run-time

protection of object's data.

Some languages, such as Ruby, support instance-private and instance-protected access

specifiers in lieu of (or in addition to) class-private and class-protected, respectively. They

differ in that they restrict access based on the instance itself, rather than the instance's class.

In addition, some languages, such as C++, support a mechanism where a function explicitly

declared as friend of the class may access the members designated as private or protected.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

69www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 70: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

6. Associations between classes

In object-oriented design and in UML, an association between two classes is a type of a link

between the corresponding objects. A (two-way) association between classes A and B

describes a relationship between each object of class A and some objects of class B, and vice

versa. Associations are often named with a verb, such as "subscribes-to".

An association role type describes the role type of an instance of a class when the instance

participates in an association. An association role type is related to each end of the

association. A role describes an instance of a class from the point of view of a situation in

which the instance participates in the association. Role types are collections of role

(instance)s grouped by their similar properties. For example, a "subscriber" role type

describes the property common to instances of the class "Person" when they participate in a

"subscribes-to" relationship with the class "Magazine". Also, a "Magazine" has the

"subscribed magazine" role type when the subscribers subscribe-to it.

Association role multiplicity describes how many instances correspond to each instance of

the other class(es) of the association. Common multiplicities are "0..1", "1..1", "1..*" and

"0..*", where the "*" specifies any number of instances. There are some special kinds of

associations between classes.

6.1Composition

Composition between class A and class B describes a has-a relationship where

instances of class B have shorter or same lifetime than the lifetime of the

corresponding instances of the enclosing class. Class B is said to be a part of class A.

This is often implemented in programming languages by allocating the data storage of

instances of class A to contain a representation of instances of class B.

Aggregation is a variation of composition that describes that instances of a class are

part of instances of the other class, but the constraint on lifetime of the instances is not

required. The implementation of aggregation is often via a pointer or reference to the

contained instance. In both cases, method implementations of the enclosing class can

invoke methods of the part class. A common example of aggregation is a list class.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

70www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 71: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

When a list's lifetime is over, it does not necessarily mean the lifetimes of the objects

within the list are also over.

6.2 Inheritance

Another type of class association is inheritance, which involves subclasses and

superclasses, also known respectively as child classes (or derived classes) and parent

classes (or base classes). If [car] was a class, then [station wagon] and [mini-van]

might be two subclasses. If [Button] is a subclass of [Control], then all buttons are

controls. In other words, inheritance is an is-a relationship between two classes.

Subclasses usually consist of several kinds of modifications (customizations) to their

respective superclasses: addition of new instance variables, addition of new methods

and overriding of existing methods to support the new instance variables.

Conceptually, a superclass should be considered as a common part of its subclasses.

This factoring of commonality is one mechanism for providing reuse. Thus, extending

a superclass by modifying the existing class is also likely to narrow its applicability in

various situations. In object-oriented design, careful balance between applicability

and functionality of superclasses should be considered. Subclassing is different from

subtyping in that subtyping deals with common behaviour whereas subclassing is

concerned with common structure.

Some programming languages (for example C++) allow multiple inheritance - they

allow a child class to have more than one parent class. This technique has been

criticized by some for its unnecessary complexity and being difficult to implement

efficiently, though some projects have certainly benefited from its use. Java, for

example has no multiple inheritance, as its designers felt that it would add

unnecessary complexity. Java instead allows inheriting from multiple pure abstract

classes (called interfaces in Java).

Sub- and superclasses are considered to exist within a hierarchy defined by the

inheritance relationship. If multiple inheritance is allowed, this hierarchy is a directed

acyclic graph (or DAG for short), otherwise it is a tree. The hierarchy has classes as

nodes and inheritance relationships as links. The levels of this hierarchy are called

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

71www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 72: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

layers or levels of abstraction. Classes in the same level are more likely to be

associated than classes in different levels.

There are two slightly different points of view as to whether subclasses of the same

class are required to be disjoint. Sometimes, subclasses of a particular class are

considered to be completely disjoint. That is, every instance of a class has exactly one

most-derived class, which is a subclass of every class that the instance has. This view

does not allow dynamic change of object's class, as objects are assumed to be created

with a fixed most-derived class. The basis for not allowing changes to object's class is

that the class is a compile-time type, which does not usually change at runtime, and

polymorphism is utilized for any dynamic change to the object's behavior, so this

ability is not necessary. And design that does not need to perform changes to object's

type will be more robust and easy-to-use from the point of view of the users of the

class.

From another point of view, subclasses are not required to be disjoint. Then there is

no concept of a most-derived class, and all types in the inheritance hierarchy that are

types of the instance are considered to be equally types of the instance. This view is

based on a dynamic classification of objects, such that an object may change its class

at runtime. Then object's class is considered to be its current structure, but changes to

it are allowed. The basis for allowing changes to object's class is a perceived

inconvenience caused by replacing an instance with another instance of a different

type, since this would require change of all references to the original instance to be

changed to refer to the new instance. When changing the object's class, references to

the existing instances do not need to be replaced with references to new instances

when the class of the object changes. However, this ability is not readily available in

all programming languages. This analysis depends on the proposition that dynamic

changes to object structure are common. This may or may not be the case in practice.

6.3 Languages without inheritance

Although class-based languages are commonly assumed to support inheritance,

inheritance is not an intrinsic aspect of the concept of classes. There are languages

that support classes yet do not support inheritance. Examples are earlier versions of

Visual Basic. These languages, sometimes called "object-based languages", do not

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

72www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 73: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

provide the structural benefits of statically type-checked interfaces for objects. This is

because in object-based languages, it is possible to use and extend data structures and

attach methods to them at run-time. This precludes the compiler or interpreter from

being able to check the type information specified in the source code as the type is

built dynamically and not defined statically. Most of these languages allow for

instance behaviour and complex operational polymorphism (see dynamic dispatch and

polymorphism).

Topic : Object-Oriented Design

Topic Objective:

At the end of this topic the student will be able to understand:

Some design principles and strategies

Input (sources) for object-oriented design

Definition/Overview:

Overview: An object contains encapsulated data and procedures grouped together to

represent an entity. The 'object interface', how the object can be interacted, is also defined.

An object-oriented program is described by the interaction of these objects. Object-oriented

design is the discipline of defining the objects and their interactions to solve a problem that

was identified and documented during object-oriented analysis. From a business perspective,

Object Oriented Design refers to the objects that make up that business. For example, in a

certain company, a business object can consist of people, data files and database tables,

artefacts, equipment, vehicles, etc. What follows is a description of the class-based subset of

object-oriented design, which does not include object prototype-based approaches where

objects are not typically obtained by instancing classes but by cloning other (prototype)

objects.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

73www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 74: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Key Points:

1. Input (sources) for object-oriented design

The input for object-oriented design is provided by the output of object-oriented analysis.

Realize that an output artefact does not need to be completely developed to serve as input of

object-oriented design; analysis and design may occur in parallel, and in practice the results

of one activity can feed the other in a short feedback cycle through an iterative process. Both

analysis and design can be performed incrementally, and the artefacts can be continuously

grown instead of completely developed in one shot. Some typical input artefacts for object-

oriented design are:

Conceptual model: Conceptual model is the result of object-oriented analysis, it captures

concepts in the problem domain. The conceptual model is explicitly chosen to be independent

of implementation details, such as concurrency or data storage.

Use case: Use case is description of sequences of events that, taken together, lead to a system

doing something useful. Each use case provides one or more scenarios that convey how the

system should interact with the users called actors to achieve a specific business goal or

function. Use case actors may be end users or other systems. In many circumstances use

cases are further elaborated into use case diagrams. Use case diagrams are used to identify the

actor (users or other systems) and the processes they perform.

System Sequence Diagram: System Sequence diagram (SSD) is a picture that shows, for a

particular scenario of a use case, the events that external actors generate, their order, and

possible inter-system events.

User interface documentations (if applicable): Document that shows and describes the look

and feel of the end product's user interface. It is not mandatory to have this, but it helps to

visualize the end-product and therefore helps the designer.

Relational data model (if applicable): A data model is an abstract model that describes how

data is represented and used. If an object database is not used, the relational data model

should usually be created before the design, since the strategy chosen for object-relational

mapping is an output of the OO design process. However, it is possible to develop the

relational data model and the object-oriented design artefacts in parallel, and the growth of an

artefact can stimulate the refinement of other artefacts.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

74www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 75: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

2. Some design principles and strategies

Dependency injection: The basic idea is that if an object depends upon having an instance of

some other object then the needed object is "injected" into the dependent object; for example,

being passed a database connection as an argument to the constructor instead of creating one

internally.

Acyclic dependencies principle: The dependency graph of packages or components should

have no cycles. This is also referred to as having a directed acyclic graph.For example,

package C depends on package B, which depends on package A. If package A also depended

on package C, then you would have a cycle.

Composite reuse principle: Favor polymorphic composition of objects over inheritance

Topic : Gui Basics

Topic Objective:

At the end of this topic the student will be able to understand:

History

Components

Post-WIMP Interfaces

Three-dimensional user interfaces

Definition/Overview:

Overview: A graphical user interface (GUI, IPA: /ˈguːi/) is a type of user interface which

allows people to interact with electronic devices such as computers; hand-held devices such

as MP3 Players, Portable Media Players or Gaming devices; household appliances and office

equipment. A GUI offers graphical icons, and visual indicators, as opposed to text-based

interfaces, typed command labels or text navigation to fully represent the information and

actions available to a user. The actions are usually performed through direct manipulation of

the graphical elements. The term GUI is historically restricted to the scope of two-

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

75www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 76: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

dimensional display screens with display resolutions capable of describing generic

information, in the tradition of the computer science research at Palo Alto Research Center

(PARC). The term GUI earlier might have been applicable to other high-resolution types of

interfaces that are non-generic, such as videogames, or not restricted to flat screens, like

volumetric displays.

Key Points:

1. History

The precursor to GUIs was invented by researchers at the Stanford Research Institute, led by

Douglas Engelbart. They developed the use of text-based hyperlinks manipulated with a

mouse for the On-Line System. The concept of hyperlinks was further refined and extended

to graphics by researchers at Xerox PARC, who went beyond text-based hyperlinks and used

a GUI as the primary interface for the Xerox Alto computer. Most modern general-purpose

GUIs are derived from this system. As a result, some people call this class of interface a

PARC User Interface (PUI) (note that PUI is also an acronym for perceptual user interface).

Ivan Sutherland developed a pointer-based system called Sketchpad in 1963. It used a light-

pen to guide the creation and manipulation of objects in engineering drawings.

The PARC User Interface consisted of graphical elements such as windows, menus, radio

buttons, check boxes and icons. The PARC User Interface employs a pointing device in

addition to a keyboard. These aspects can be emphasized by using the alternative acronym

WIMP, which stands for Windows, Icons, Menus and Pointing device.

Following PARC the first GUI-centric computer operating model was the Xerox 8010 Star

Information System in 1981 followed by the Apple Lisa (which presented concept of menu

bar as well as window controls), in 1982 and the Atari ST and Commodore Amiga in 1985.

The GUIs familiar to most people today are Microsoft Windows, Mac OS X, and the X

Window System interfaces. Apple, IBM and Microsoft used many of Xerox's ideas to

develop products, and IBMs Common User Access specifications formed the basis of the user

interface found in Microsoft Windows, IBM OS/2 Presentation Manager, and the Unix Motif

toolkit and window manager. These ideas evolved to create the interface found in current

versions of Microsoft Windows, as well as in Mac OS X and various desktop environments

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

76www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 77: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

for Unix-like operating systems, such as Linux. Thus most current GUIs have largely

common idioms.

2. Components

A GUI uses a combination of technologies and devices to provide a platform the user can

interact with, for the tasks of gathering and producing information. The most common

combination in GUIs is the WIMP paradigm, especially in personal computers. This style of

interaction uses a physical input device to control the position of a cursor and presents

information organized in windows and represented with icons. Available commands are

compiled together in menus and actioned through the pointing device. A window manager

facilitates the interactions between windows, applications, and the windowing system. The

windowing system handles hardware devices such as pointing devices and graphics hardware,

as well as the positioning of the cursor. In personal computers all these elements are modelled

through a desktop metaphor, to produce a simulation called a desktop environment in which

the display represents a desktop, upon which documents and folders of documents can be

placed. Window managers and other software combine to simulate the desktop environment

with varying degrees of realism.

3. Post-WIMP Interfaces

Smaller mobile devices such as PDAs and smartphones typically use the WIMP elements

with different unifying metaphors, due to constraints in space and available input devices.

Applications for which WIMP is not well suited may use newer interaction techniques,

collectively named as post-WIMP user interfaces.

Some touch-screen-based devices such as Apple's iPhone currently use post-WIMP styles of

interaction. The iPhone's use of more than one finger in contact with the screen allows

actions such as pinching and rotating, which are not supported by a single pointer and mouse.

A class of GUIs sometimes referred to as post-WIMP include 3D compositing window

manager such as Compiz, Desktop Window Manager, and LG3D. Some post-WIMP

interfaces may be better suited for applications which model immersive 3D environments,

such as Google Earth.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

77www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 78: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

4. Three-dimensional user interfaces

For typical computer displays, three-dimensional is a misnomertheir displays are two-

dimensional. Three-dimensional images are projected on them in two dimensions. Since this

technique has been in use for many years, the recent use of the term three-dimensional must

be considered a declaration by equipment marketers that the speed of three dimension to two

dimension projection is adequate to use in standard GUIs.

Three-dimensional GUIs are quite common in science fiction literature and movies, such as

in Jurassic Park, which features Silicon Graphics' three-dimensional file manager, "File

system navigator", an actual file manager that never got much widespread use as the user

interface for a Unix computer. In fiction, three-dimensional user interfaces are often

immersible environments like William Gibson's Cyberspace or Neal Stephenson's Metaverse.

Three-dimensional graphics are currently mostly used in computer games, art and computer-

aided design (CAD). There have been several attempts at making three-dimensional desktop

environments like Sun's Project Looking Glass or SphereXP from Sphere Inc. A three-

dimensional computing environment could possibly be used for collaborative work. For

example, scientists could study three-dimensional models of molecules in a virtual reality

environment, or engineers could work on assembling a three-dimensional model of an

airplane. This is a goal of the Croquet project and Project Looking Glass.

The use of three-dimensional graphics has become increasingly common in mainstream

operating systems, but mainly been confined to creating attractive interfaceseye candyrather

than for functional purposes only possible using three dimensions. For example, user

switching is represented by rotating a cube whose faces are each user's workspace, and

window management is represented in the form of Expos on Mac OS X, or via a Rolodex-

style flipping mechanism in Windows Vista (see Windows Flip 3D). In both cases, the

operating system transforms windows on-the-fly while continuing to update the content of

those windows.

Interfaces for the X Window System have also implemented advanced three-dimensional user

interfaces through compositing window managers such as Beryl and Compiz using the

AIGLX or XGL architectures, allowing for the usage of OpenGL to animate the user's

interactions with the desktop.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

78www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 79: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Another branch in the three-dimensional desktop environment is the three-dimensional GUIs

that take the desktop metaphor a step further, like the BumpTop, where a user can manipulate

documents and windows as if they were "real world" documents, with realistic movement and

physics.

The Zooming User Interface (ZUI) is a related technology that promises to deliver the

representation benefits of 3D environments without their usability drawbacks of orientation

problems and hidden objects. It is a logical advancement on the GUI, blending some three-

dimensional movement with two-dimensional or "2.5D" vector objects.

Topic : Graphics

Topic Objective:

At the end of this topic the student will be able to understand:

History

Uses

Definition/Overview:

Overview: Graphics (from Greekγραφικός; see -graphy) are visual presentations on some

surface, such as a wall, canvas, computer screen, paper, or stone to brand, inform, illustrate,

or entertain. Examples are photographs, drawings, Line Art, graphs, diagrams, typography,

numbers, symbols, geometric designs, maps, engineering drawings, or other images. Graphics

often combine text, illustration, and color. Graphic design may consist of the deliberate

selection, creation, or arrangement of typography alone, as in a brochure, flier, poster, web

site, or book without any other element. Clarity or effective communication may be the

objective, association with other cultural elements may be sought, or merely, the creation of a

distinctive style. Graphics can be functional or artistic. The latter can be a recorded version,

such as a photograph, or an interpretation by a scientist to highlight essential features, or an

artist, in which case the distinction with imaginary graphics may become blurred.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

79www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 80: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Key Points:

1. History

The earliest graphics known to anthropologists studying prehistoric periods are cave

paintings and markings on boulders, bone, ivory, and antlers, which were created during the

Upper Palaeolithic period from 40,00010,000 B.C. or earlier. Many of these were found to

record astronomical, seasonal, and chronological details. Some of the earliest graphics and

drawings known to the modern world, from almost 6,000 years ago, are that of engraved

stone tablets and ceramic cylinder seals, marking the beginning of the historic periods and the

keeping of records for accounting and inventory purposes. Records from Egypt predate these

and papyrus was used by the Egyptians as a material on which to plan the building of

pyramids; they also used slabs of limestone and wood. From 600250 BC, the Greeks played a

major role in geometry. They used graphics to represent their mathematical theories such as

the Circle Theorem and the Pythagorean theorem. In art, "graphics" is often used to

distinguish work in a monotone and made up of lines, as opposed to painting.

Drawing generally involves making marks on a surface by applying pressure from a tool, or

moving a tool across a surface. Common tools are graphite pencils, pen and ink, inked

brushes, wax color pencils, crayons, charcoals, pastels, and markers. Digital tools which

simulate the effects of these are also used. The main techniques used in drawing are line

drawing, hatching, crosshatching, random hatching, scribbling, stippling, blending, and

shading. Drawing is generally considered distinct from painting, in which colored pigments

are suspended in a liquid medium and are usually applied with a brush. Notable great drawers

include Michelangelo, Rembrandt, Raphael and Leonardo da Vinci. Many people choose

drawing as a main art style, or they may use it to make sketches for paintings, sculptures and

other types of art.

There are two types of computer graphics: raster graphics, where each pixel is separately

defined (as in a digital photograph), and vector graphics, where mathematical formulas are

used to draw lines and shapes, which are then interpreted at the viewer's end to produce the

graphic. Using vectors results in infinitely sharp graphics and often smaller files, but, when

complex, vectors take time to render and may have larger filesizes than a raster equivalent.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

80www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 81: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

A screenshot from the 2007 PC Video game Crysis displaying extremely photo-realistic Real-

time Computer graphicsIn 1950, the first computer-driven display was attached to MIT's

Whirlwind I computer to generate simple pictures. This was followed by MIT's TX-0 and

TX-2, interactive computing which increased interest in computer graphics during the late

1950s. In 1962, Ivan Sutherland invented Sketchpad, an innovative program that influenced

alternative forms of interaction with computers.

In the mid-1960s, large computer graphics research projects were begun at MIT, General

Motors, Bell Labs, and Lockheed Corporation. Douglas T. Ross of MIT developed an

advanced compiler language for graphics programming. S.A.Coons, also at MIT, and J. C.

Ferguson at Boeing, began work in sculptured surfaces. GM developed their DAC-1 system,

and other companies, such as Douglas, Lockheed, and McDonnell, also made significant

developments. In 1968, ray tracing was invented by Apple

During the late 1970s, personal computers became more powerful, capable of drawing both

basic and complex shapes and designs. In the 1980s, artists and graphic designers began to

see the personal computer, particularly the Commodore Amiga and Macintosh, as a serious

design tool, one that could save time and draw more accurately than other methods. 3D

computer graphics became possible in the late 1980s with the powerful SGI computers,

which were later used to create some of the first fully computer-generated short films at

Pixar. The Macintosh remains one of the most popular tools for computer graphics in graphic

design studios and businesses.

Modern computer systems, dating from the 1980s and onwards, often use a graphical user

interface (GUI) to present data and information with symbols, icons and pictures, rather than

text. Graphics are one of the five key elements of multimedia technology.

3D graphics became more popular in the 1990s in gaming, multimedia and animation. In

1996, Quake, one of the first fully 3D games, was released. In 1995, Toy Story, the first full-

length computer-generated animation film, was released in cinemas worldwide. Since then,

computer graphics have become more accurate and detailed, due to more advanced

computers and better 3D modelling software applications, such as Maya (software),3D Studio

Max,Cinema 4D.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

81www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 82: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Another use of computer graphics is screensavers, originally intended to preventing the

layout of much-used GUIs from 'burning into' the computer screen. They have since evolved

into true pieces of art, their practical purpose obsolete; modern screens are not susceptible to

such burn in artifacts.

In the 1990s, Internet speeds increased, and Internet browsers capable of viewing images

were released, the first being Mosaic. Websites began to use the GIF format to display small

graphics, such as banners, advertisements and navigation buttons, on web pages. Modern web

browsers can now display JPEG, PNG and increasingly, SVG images in addition to GIFs on

web pages. SVG, and to some extent VML, support in some modern web browsers have

made it possible to display vector graphics that are clear at any size. Plugins expand the web

browser functions to display animated, interactive and 3-D graphics contained within file

formats such as SWF and X3D.

Modern web graphics can be made with software such as Adobe Photoshop, the GIMP, or

Corel Paint Shop Pro. Users of Microsoft Windows have MS Paint, which many find to be

lacking in features. This is because MS Paint is a drawing package and not a graphics

package.

Numerous platforms and websites have been created to cater to web graphics artists and to

host their communities. A growing number of people use create internet forum

signaturesgenerally appearing after a user's postand other digital artwork, such as photo

manipulations and large graphics.

2. Uses

Graphics are visual elements often used to point readers and viewers to particular

information. They are also used to supplement text in an effort to aid readers in their

understanding of a particular concept or make the concept more clear or interesting. Popular

magazines, such as TIME, Wired and Newsweek, usually contain graphic material in

abundance to attract readers, unlike the majority of scholarly journals. In computing, they are

used to create a graphical interface for the user; and graphics are one of the five key elements

of multimedia technology. Graphics are among the primary ways of advertising the sale of

goods or services.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

82www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 83: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Graphics are commonly used in business and economics to create financial charts and tables.

The term Business Graphics came into use in the late 1970s, when personal computers

became capable of drawing graphs and charts instead of using a tabular format. Business

Graphics can be used to highlight changes over a period of time.

Advertising is one of the most profitable uses of graphics; artists often do advertising work or

take advertising potential into account when creating art, to increase the chances of selling

the artwork.

The use of graphics for overtly political purposescartoons, graffiti, poster art, flag design,

etcis a centuries old practice which thrives today in every part of the world. The Northern

Irish murals are one such example. Graphics are heavily used in textbooks, especially those

concerning subjects such as geography, science, and mathematics, in order to illustrate

theories and concepts, such as the human anatomy. Diagrams are also used to label

photographs and pictures. Educational animation is an important emerging field of graphics.

Animated graphics have obvious advantages over static graphics when explaining subject

matter that changes over time. The Oxford Illustrated Dictionary uses graphics and technical

illustrations to make reading material more interesting and easier to understand. In an

encyclopedia, graphics are used to illustrate concepts and show examples of the particular

topic being discussed. In order for a graphic to function effectively as an educational aid, the

learner must be able to interpret it successfully. This interpretative capacity is one aspect of

graphicacy.

Topic : Event-Driven Programming

Topic Objective:

At the end of this topic the student will be able to understand:

Introduction

Contrast with batch programming

Creating event handlers

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

83www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 84: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Definition/Overview:

Overview: In computer programming, event-driven programming or event-based

programming is a programming paradigm in which the flow of the program is determined by

events i.e., sensor outputs or user actions (mouse clicks, key presses) or messages from other

programs or threads.

Key Points:

1. Introduction

Event-driven programming can also be defined as an application architecture technique in

which the application has a main loop which is clearly divided down to two sections: the first

is event selection (or event detection), and the second is event handling. In embedded systems

the same may be achieved using interrupts instead of a constantly running main loop; in that

case the former portion of the architecture resides completely in hardware. Event-driven

programs can be written in any language, although the task is easier in languages that provide

high-level abstractions, such as closures. Some integrated development environments provide

code generation assistants that automate the most repetitive tasks required for event handling.

2. Contrast with batch programming

In contrast, in batch programming, the flow is determined by the programmer. Although

batch programming is the style taught in beginning programming classes, the more complex

event-driven programming is the standard architecture of modern interactive programs. At

first sight, the event-driven program seems more cumbersome and for such a trivial task is

indeed so. However, the second program can be generalized far more easily than the first.

Instead of checking just for a number entry we may add code to check whether any of several

events has occurred. Then for each event we can execute a particular piece of code that is

commonly referred to as an event handler.

3. Creating event handlers

The first step in developing an event-driven program is to write a series of subroutines, or

methods, called event-handler routines. These routines handle the events that the main

program will respond to. For example, in a GUI program, we might be interested in a single

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

84www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 85: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

(as opposed to a double) left-button mouse-click on a command button. So a routine would be

written to respond to such an event. The routine might open another window, save data to a

database or exit the application. Many modern day programming environments provide the

programmer with event templates so that the programmer need only supply the event code.

The second step is to bind event handlers to events, so that the correct function is called when

the event takes place. Graphical editors combine the first two steps: double-click on a button,

and the editor creates an (empty) event handler associated with the user clicking the button

and opens a text window so you can edit the event handler.

The third step in developing an event-driven program is to write the main loop: a function

that checks for events, and then calls the matching event handler. Most event-driven

programming environments already provide this main loop, so it need not be rewritten.

In Section 3 of this course you will cover these topics:Creating User Interfaces

Applets And Multimedia

Exception Assertions

Binary I/O

Recursion

Lists, Stacks, Queues, Trees, And Heaps

Generics

Topic : Creating User Interfaces

Topic Objective:

At the end of this topic the student will be able to understand:

Introduction

Usability

User interfaces in computing

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

85www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 86: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Definition/Overview:

Overview: The user interface (also known as Human Computer Interface or Man-Machine

Interface (MMI)) is the aggregate of means by which peoplethe usersinteract with the

systema particular machine, device, computer program or other complex tool. The user

interface provides means of:

Input, allowing the users to manipulate a system

Output, allowing the system to indicate the effects of the users' manipulation.

Key Points:

1. Introduction

To work with a system, users have to be able to control the system and assess the state of the

system. For example, when driving an automobile, the driver uses the steering wheel to

control the direction of the vehicle, and the accelerator pedal, brake pedal and gearstick to

control the speed of the vehicle. The driver perceives the position of the vehicle by looking

through the windscreen and exact speed of the vehicle by reading the speedometer. The user

interface of the automobile is on the whole composed of the instruments the driver can use to

accomplish the tasks of driving and maintaining the automobile.

The term user interface is often used in the context of computer systems and electronic

devices. The user interface of a mechanical system, a vehicle or an industrial installation is

sometimes referred to as the Human-Machine Interface (HMI). HMI is a modification of the

original term MMI (Man-Machine Interface). In practice, the abbreviation MMI is still

frequently used although some may claim that MMI stands for something different now.

Another abbreviation is HCI, but is more commonly used for Human-computer interaction

than Human-computer interface. Other terms used are Operator Interface Console (OIC) and

Operator Interface Terminal (OIT). However it is abbreviated, the terms refer to the 'layer'

that separates a human that is operating a machine from the machine itself.

In science fiction, HMI is sometimes used to refer to what is better described as direct neural

interface. However, this latter usage is seeing increasing application in the real-life use of

(medical) prosthesesthe artificial extension that replaces a missing body part (e.g., cochlear

implants). The system may expose several user interfaces to serve different kinds of users.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

86www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 87: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

For example, a computerized library database might provide two user interfaces, one for

library patrons (limited set of functions, optimized for ease of use) and the other for library

personnel (wide set of functions, optimized for efficiency).

In some circumstance computers might observe the user, and react according to their actions

without specific commands. A means of tracking parts of the body is required, and sensors

noting the position of the head, direction of gaze and so on have been used experimentally.

This is particularly relevant to immersive interfaces.

2. Usability

The design of a user interface affects the amount of effort the user must expend to provide

input for the system and to interpret the output of the system, and how much effort it takes to

learn how to do this. Usability is the degree to which the design of a particular user interface

takes into account the human psychology and physiology of the users, and makes the process

of using the system effective, efficient and satisfying. Usability is mainly a characteristic of

the user interface, but is also associated with the functionalities of the product and the process

to design it. It describes how well a product can be used for its intended purpose by its target

users with efficiency, effectiveness, and satisfaction, also taking into account the

requirements from its context of use.

3. User interfaces in computing

In computer science and human-computer interaction, the user interface (of a computer

program) refers to the graphical, textual and auditory information the program presents to the

user, and the control sequences (such as keystrokes with the computer keyboard, movements

of the computer mouse, and selections with the touchscreen) the user employs to control the

program.

3.1 Types

Currently (as of 2009[update]) the following types of user interface are the most

common:

o Graphical user interfaces (GUI) accept input via devices such as computer

keyboard and mouse and provide articulated graphical output on the computer

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

87www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 88: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

monitor. There are at least two different principles widely used in GUI design:

Object-oriented user interfaces (OOUIs) and application oriented

interfaces[verification needed].

o Web-based user interfaces or web user interfaces (WUI) accept input and

provide output by generating web pages which are transmitted via the Internet

and viewed by the user using a web browser program. Newer implementations

utilize Java, AJAX, Adobe Flex, Microsoft .NET, or similar technologies to

provide realtime control in a separate program, eliminating the need to refresh

a traditional HTML based web browser. Administrative web interfaces for

web-servers, servers and networked computers are called Control panel.

User interfaces that are common in various fields outside desktop computing:

o Command line interfaces, where the user provides the input by typing a

command string with the computer keyboard and the system provides output

by printing text on the computer monitor. Used for system administration tasks

etc.

o Tactile interfaces supplement or replace other forms of output with haptic

feedback methods. Used in computerized simulators etc.

o Touch interfaces are graphical user interfaces using a touchscreen display as a

combined input and output device. Used in many types of point of sale,

industrial processes and machines, self-service machines etc.

Other types of user interfaces:

o Attentive user interfaces manage the user attention deciding when to interrupt

the user, the kind of warnings, and the level of detail of the messages

presented to the user.

o Batch interfaces are non-interactive user interfaces, where the user specifies all

the details of the batch job in advance to batch processing, and receives the

output when all the processing is done. The computer does not prompt for

further input after the processing has started.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

88www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 89: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

o Conversational Interface Agents attempt to personify the computer interface in

the form of an animated person, robot, or other character (such as Microsoft's

Clippy the paperclip), and present interactions in a conversational form.

o Crossing-based interfaces are graphical user interfaces in which the primary task

consists in crossing boundaries instead of pointing.

o Gesture interfaces are graphical user interfaces which accept input in a form of

hand gestures, or mouse gestures sketched with a computer mouse or a stylus.

o Intelligent user interfaces are human-machine interfaces that aim to improve the

efficiency, effectiveness, and naturalness of human-machine interaction by

representing, reasoning, and acting on models of the user, domain, task,

discourse, and media (e.g., graphics, natural language, gesture).

o Multi-screen interfaces, employ multiple displays to provide a more flexible

interaction. This is often employed in computer game interaction in both the

commercial arcades and more recently the handheld markets.

o Noncommand user interfaces, which observe the user to infer his / her needs and

intentions, without requiring that he / she formulate explicit commands.

o Object-oriented User Interface (OOUI)

o Reflexive user interfaces where the users control and redefine the entire system

via the user interface alone, for instance to change its command verbs.

Typically this is only possible with very rich graphic user interfaces.

o Tangible user interfaces, which place a greater emphasis on touch and physical

environment or its element.

o Text user interfaces are user interfaces which output text, but accept other form

of input in addition to or in place of typed command strings.

o Voice user interfaces, which accept input and provide output by generating

voice prompts. The user input is made by pressing keys or buttons, or

responding verbally to the interface.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

89www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 90: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

o Natural-Language interfaces - Used for search engines and on webpages. User

types in a question and waits for a response.

o Zero-Input interfaces get inputs from a set of sensors instead of querying the

user with input dialogs.

o Zooming user interfaces are graphical user interfaces in which information

objects are represented at different levels of scale and detail, and where the

user can change the scale of the viewed area in order to show more detail.

Topic : Applets And Multimedia

Topic Objective:

At the end of this topic the student will be able to understand:

Attributes of Applets

Multimedia

Definition/Overview:

Overview: An applet is a software component that runs in the context of another program,

for example a web browser. An applet usually performs a very narrow function that has no

independent use. Hence, it is an application -let. The term was used in AppleScript in 1993,

but predates that by nearly a decade. The word applet could alternatively be used to describe

a small standalone application, such as those typically bundled with operating systems, for

example a calculator program or text editor.

Multimedia is media and content that utilizes a combination of different content forms. The

term can be used as a noun (a medium with multiple content forms) or as an adjective

describing a medium as having multiple content forms. The term is used in contrast to media

which only utilize traditional forms of printed or hand-produced material. Multimedia

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

90www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 91: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

includes a combination of text, audio, still images, animation, video, and interactivity content

forms.

Key Points:

1. Attributes of Applets

An applet is distinguished from "subroutine" by several features:

First, it executes only on the "client" platform environment of a system, as contrasted from

"servlet". As such, an applet provides functionality or performance beyond the default

capabilities of its container (the browser).

Also, in contrast with a subroutine, certain capabilities are restricted by the container.

An applet is written in a language that is different from the scripting or HTML language

which invokes it. The applet is written in a compiled language, while the scripting language

of the container is an interpreted language, hence the greater performance or functionality of

the applet. Unlike a "subroutine", a complete web component can be implemented as an

applet.

Unlike a program, an applet cannot run independently; an applet features display and

graphics and often interacts with the human user. However, they are usually stateless and

have restricted security privileges. The applet must run in a container, which is provided by a

host program, through a plugin, or a variety of other applications including mobile devices

that support the applet programming model.

2. Multimedia

Multimedia is usually recorded and played, displayed or accessed by information content

processing devices, such as computerized and electronic devices, but can also be part of a live

performance. Multimedia (as an adjective) also describes electronic media devices used to

store and experience multimedia content. Multimedia is similar to traditional mixed media in

fine art, but with a broader scope. The term "rich media" is synonymous for interactive

multimedia. Hypermedia can be considered one particular multimedia application.

Multimedia presentations may be viewed in person on stage, projected, transmitted, or played

locally with a media player. A broadcast may be a live or recorded multimedia presentation.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

91www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 92: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Broadcasts and recordings can be either analog or digital electronic media technology. Digital

online multimedia may be downloaded or streamed. Streaming multimedia may be live or on-

demand.

Multimedia games and simulations may be used in a physical environment with special

effects, with multiple users in an online network, or locally with an offline computer, game

system, or simulator.

The various formats of technological or digital multimedia may be intended to enhance the

users' experience, for example to make it easier and faster to convey information. A

lasershow is a live multimedia performance. Enhanced levels of interactivity are made

possible by combining multiple forms of media content. Online multimedia is increasingly

becoming object-oriented and data-driven, enabling applications with collaborative end-user

innovation and personalization on multiple forms of content over time. Examples of these

range from multiple forms of content on Web sites like photo galleries with both images

(pictures) and title (text) user-updated, to simulations whose co-efficients, events,

illustrations, animations or videos are modifiable, allowing the multimedia "experience" to be

altered without reprogramming. In addition to seeing and hearing, Haptic technology enables

virtual objects to be felt. Emerging technology involving illusions of taste and smell may also

enhance the multimedia experience.

Multimedia represents the convergence of text, pictures, video and sound into a single form.

The power of multimedia and the Internet lies in the way in which information is linked.

Multimedia and the Internet require a completely new approach to writing. The style of

writing that is appropriate for the 'on-line world' is highly optimized and designed to be able

to be quickly scanned by readers. A good site must be made with a specific purpose in mind

and a site with good interactivity and new technology can also be useful for attracting

visitors. The site must be attractive and innovative in its design, function in terms of its

purpose, easy to navigate, frequently updated and fast to download. When users view a page,

they can only view one page at a time. As a result, multimedia users must create a mental

model of information structure. Patrick Lynch, author of the Yale University Web Style

Manual, states that users need predictability and structure, with clear functional and graphical

continuity between the various components and subsections of the multimedia production. In

this way, the home page of any multimedia production should always be a landmark, able to

be accessed from anywhere within a multimedia piece.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

92www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 93: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Topic : Exception Assertions

Topic Objective:

At the end of this topic the student will be able to understand:

Introduction

Exception safety

Exception support in programming languages

Checked exceptions

Exception synchronity

Condition systems

Definition/Overview:

Overview: Assertions can be a form of documentation: they can describe the state the code

expects to find before it runs (its preconditions), and the state the code expects to result in

when it is finished running (postconditions); they can also specify invariants of a class. In

Eiffel, such assertions are integrated into the language and are automatically extracted to

document the class. This forms an important part of the method of design by contract. This

approach is also useful in languages that do not explicitly support it: the advantage of using

assertion statements rather than assertions in comments is that assertions can be checked

every time the program is run; if the assertion no longer holds, an error can be reported. This

prevents the code from getting out of sync with the assertions (a problem that can occur with

comments). Exception handling is a programming language construct or computer hardware

mechanism designed to handle the occurrence of a condition that changes the normal flow of

execution. For signaling conditions that are part of the normal flow of execution, see the

concepts of signal and event handler. In general, the current state will be saved in a

predefined location and the execution will switch to a predefined handler. Depending on the

situation, the handler may later resume the execution at the original location, using the saved

information to restore the original state. For example, an exception that will usually be

resumed is a page fault, while a division by zero usually cannot be resolved transparently.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

93www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 94: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Key Points:

1. Introduction

From the processing point of view, hardware interrupts are similar to resumable exceptions,

although they are usually not related to the current program flow.

From the point of view of the author of a routine, raising an exception is a useful way to

signal that the routine could not execute normally. For example, when an input argument is

invalid (a zero denominator in division) or when a resource it relies on is unavailable (like a

missing file, or a hard disk error). In systems without exceptions, routines would need to

return some special error code. However, this is sometimes complicated by the semipredicate

problem, in which users of the routine need to write extra code to distinguish normal return

values from erroneous ones.

In runtime engine environments such as Java or .NET, there exist tools that attach to the

runtime engine and every time that an exception of interest occurs, they record debugging

information that existed in memory at the time the exception was thrown (call stack and heap

values). These tools are called Automated Exception Handling or Error Interception tools and

provide 'root-cause' information for exceptions.

Contemporary applications face many design challenges when considering exception

handling strategies. Particularly in modern enterprise level applications, exceptions must

often cross process boundaries and machine boundaries. Part of designing a solid exception

handling strategy is recognizing when a process has failed to the point where it cannot be

economically handled by the software portion of the process. At such times, it is very

important to present exception information to the appropriate stakeholders.

2. Exception safety

For instance, consider a smart vector type, such as C++'s std::vector or Java's ArrayList.

When an item x is added to a vector v, the vector must actually add x to the internal list of

objects and also update a count field that says how many objects are in v. It may also need to

allocate new memory if the existing capacity isn't large enough. This memory allocation may

fail and throw an exception. Because of this, a vector that provides failure transparency

would be very difficult or impossible to write. However, the vector may be able to offer the

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

94www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 95: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

strong exception guarantee fairly easily; in this case, either the insertion of x into v will

succeed, or v will remain unchanged. If the vector provides only the basic exception safety

guarantee, if the insertion fails, v may or may not contain x, but at least it will be in a

consistent state. However, if the vector makes only the minimal guarantee, it's possible that

the vector may be invalid. For instance, perhaps the size field of v was incremented but x

wasn't actually inserted, making the state inconsistent. Of course, with no guarantee, the

program may crash; perhaps the vector needed to expand but couldn't allocate the memory

and blindly ploughs ahead as if the allocation succeeded, touching memory at an invalid

address. Usually at least basic exception safety is required. Failure transparency is difficult to

implement, and is usually not possible in libraries where complete knowledge of the

application is not available.

The point of exception handling routines is to ensure that the code can handle error

conditions. In order to establish that exception handling routines are sufficiently robust, it is

necessary to present the code with a wide spectrum of invalid or unexpected inputs, such as

can be created via software fault injection and mutation testing (which is also sometimes

referred to as fuzz testing). One of the most difficult types of software for which to write

exception handling routines is protocol software, since a robust protocol implementation must

be prepared to receive input that does not comply with the relevant specification(s).

In order to ensure that meaningful regression analysis can be conducted throughout a

software development lifecycle process, any exception handling verification should be highly

automated, and the test cases must be generated in a scientific, repeatable fashion. Several

commercially available systems exist that perform such testing, including the Service

Assurance Platform from Mu Dynamic which can verify exception handling for many

common protocol implementation.

3. Exception support in programming languages

Many computer languages, such as most .NET languages, Actionscript, Ada, C++, D,

ECMAScript, Eiffel, Java, ML, Object Pascal (e.g. Delphi, Free Pascal, and the like),

Objective-C, Ocaml, PHP (as of version 5), PL/1, Prolog, Python, REALbasic, Ruby, Visual

Prolog, have built-in support for exceptions and exception handling. In those languages, the

advent of an exception (more precisely, an exception handled by the language) unwinds the

stack of function calls until an exception handler is found. That is, if function f contains a

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

95www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 96: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

handler H for exception E, calls function g, which in turn calls function h, and an exception E

occurs in h, then functions h and g will be terminated, and H in f will handle E. Excluding

minor syntactic differences, there are only a couple of exception handling styles in use. In the

most popular style, an exception is initiated by a special statement (throw, or raise) with an

exception object (e.g. with Java or Object Pascal) or a value of a special extendable

enumerated type (e.g. with Ada). The scope for exception handlers starts with a marker

clause (try, or the language's block starter such as begin) and ends in the start of the first

handler clause (catch, except, rescue). Several handler clauses can follow, and each can

specify which exception types it handles and what name it uses for the exception object. A

few languages also permit a clause (else) that is used in case no exception occurred before the

end of the handler's scope was reached. More common is a related clause (finally, or ensure)

that is executed whether an exception occurred or not, typically to release resources acquired

within the body of the exception-handling block. Notably, C++ does not need and does not

provide this construct, and the Resource-Acquisition-Is-Initialization technique is used to free

such resources instead. In its whole, exception handling code might look like this (in Java-

like pseudocode; note that an exception type called EmptyLineException would need to be

declared somewhere):

4. Checked exceptions

The designers of Java devisedchecked exceptions , which are a special set of exceptions. The

checked exceptions that a method may raise are part of the method's signature. For instance,

if a method might throw an IOException, it must declare this fact explicitly in its method

signature. Failure to do so raises a compile-time error.

This is related to exception checkers that exist at least for OCaml . The external tool for

OCaml is both transparent (i.e. it does not require any syntactic annotations) and facultative

(i.e. it is possible to compile and run a program without having checked the exceptions,

although this is not suggested for production code).

The CLU programming language had a feature with the interface closer to what Java has

introduced later. A function could raise only exceptions listed in its type, but any leaking

exceptions from called functions would automatically be turned into the sole runtime

exception, failure, instead of resulting in compile-time error. Later, Modula-3 had a similar

feature. These features don't include the compile time checking which is central in the

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

96www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 97: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

concept of checked exceptions, and hasn't (as of 2006) been incorporated into major

programming languages other than Java.

4.1 Pros and cons

Checked exceptions can, at compile time, greatly reduce (but not entirely eliminate)

the incidence of unhandled exceptions surfacing at runtime in a given application; the

unchecked exceptions (RuntimeExceptions and Errors) can still go unhandled.

However, some see checked exceptions as a nuisance, syntactic salt that either

requires large throws declarations, often revealing implementation details and

reducing encapsulation, or encourages the (ab)use of poorly-considered try/catch

blocks that can potentially hide legitimate exceptions from their appropriate handlers.

The problem is more evident considering what happens to code over time. An

interface may be declared to throw exceptions X & Y. In a later version of the code, if

one wants to throw exception Z, it would make the new code incompatible with the

earlier uses. Furthermore, with the adapter pattern, where one body of code declares

an interface that is then implemented by a different body of code so that code can be

plugged in and called by the first, the adapter code may have a rich set of exceptions

to describe problems, but is forced to use the exception types declared in the interface.

Others do not consider this a nuisance as it is possible to reduce the number of

declared exceptions by either declaring a superclass of all potentially thrown

exceptions or by defining and declaring exception types that are suitable for the level

of abstraction of the called method, and mapping lower level exceptions to these

types, preferably wrapped using the exception chaining in order to preserve the root

cause. In addition, it's very possible that in the example above of the changing

interface that the calling code would need to be modified as well, since in some sense

the exceptions a method may throw are part of the method's implicit interface

anyway.

A simple throws Exception declaration or catch (Exception e) is always sufficient to

satisfy the checking. While this technique is sometimes useful, it effectively

circumvents the checked exception mechanism, so it should only be used after careful

consideration. Additionally, throws Exception forces all calling code to do the same.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

97www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 98: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

One prevalent view is that unchecked exception types should not be handled, except

maybe at the outermost levels of scope, as they often represent scenarios that do not

allow for recovery: Runtime Exceptions frequently reflect programming defects, and

Errors generally represent unrecoverable JVM failures. The view is that, even in a

language that supports checked exceptions, there are cases where the use of checked

exceptions is not appropriate.

5. Exception synchronity

Somewhat related with the concept of checked exceptions is exception synchronity.

Synchronous exceptions happen at a specific program statement whereas asynchronous

exceptions can raise practically anywhere. It follows that asynchronous exception handling

can't be required by the compiler. They are also difficult to program with. Examples of

naturally asynchronous events include pressing Ctrl-C to interrupt a program, and receiving a

signal such as "stop" or "suspend" from another thread of execution. Programming languages

typically deal with this by limiting asynchronity, for example Java has lost thread stopping

and resuming. Instead, there can be semi-asynchronous exceptions that only raise in suitable

locations of the program or synchronously.

6. Condition systems

Common Lisp, Dylan and Smalltalk have a Condition system which encompasses the

aforementioned exception handling systems. In those languages or environments the advent

of a condition (a "generalisation of an error" according to Kent Pitman) implies a function

call, and only late in the exception handler the decision to unwind the stack may be taken.

Conditions are a generalization of exceptions. When a condition arises, an appropriate

condition handler is searched for and selected, in stack order, to handle the condition.

Conditions which do not represent errors may safely go unhandled entirely; their only

purpose may be to propagate hints or warnings toward the user.

6.1 Continuable exceptions

This is related to the so-called resumption model of exception handling, in which

some exceptions are said to be continuable: it is permitted to return to the expression

that signaled an exception, after having taken corrective action in the handler. The

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

98www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 99: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

condition system is generalized thus: within the handler of a non-serious condition

(a.k.a. continuable exception), it is possible to jump to predefined restart points (a.k.a.

restarts) that lie between the signaling expression and the condition handler. Restarts

are functions closed over some lexical environment, allowing the programmer to

repair this environment before exiting the condition handler completely or unwinding

the stack even partially.

6.2 Restarts separate mechanism from policy

Condition handling moreover provides a separation of mechanism from policy.

Restarts provide various possible mechanisms for recovering from error, but do not

select which mechanism is appropriate in a given situation. That is the province of the

condition handler, which (since it is located in higher-level code) has access to a

broader view.

An example: Suppose there is a library function whose purpose is to parse a single

syslog file entry. What should this function do if the entry is malformed? There is no

one right answer, because the same library could be deployed in programs for many

different purposes. In an interactive log-file browser, the right thing to do might be to

return the entry unparsed, so the user can see it -- but in an automated log-

summarizing program, the right thing to do might be to supply null values for the

unreadable fields, but abort with an error if too many entries have been malformed.

That is to say, the question can only be answered in terms of the broader goals of the

program, which are not known to the general-purpose library function. Nonetheless,

exiting with an error message is only rarely the right answer. So instead of simply

exiting with an error, the function may establish restarts offering various ways to

continue -- for instance, to skip the log entry, to supply default or null values for the

unreadable fields, to ask the user for the missing values, or to unwind the stack and

abort processing with an error message. The restarts offered constitute the

mechanisms available for recovering from error; the selection of restart by the

condition handler supplies the policy.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

99www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 100: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Topic : Binary I/O

Topic Objective:

At the end of this topic the student will be able to understand:

Introduction

IBM PC-compatible BIOS Chips

BIOS chip vulnerabilities

Changing role of the BIOS

Definition/Overview:

Overview: In computing, the Basic Input/Output System (BIOS) , also known as the System

BIOS, is a de facto standard defining a firmware interface for IBM PC Compatible

computers. The BIOS is boot firmware, designed to be the first code run by a PC when

powered on. The initial function of the BIOS is to identify, test, and initialize system devices

such as the video display card, hard disk, and floppy disk and other hardware. This is to

prepare the machine into a known state, so that software stored on compatible media can be

loaded, executed, and given control of the PC. This process is known as booting, or booting

up, which is short for bootstrapping.

Key Points:

1. Introduction

BIOS programs are stored on a chip and are built to work with various devices that make up

the complementary chipset of the system. They provide a small library of basic input/output

functions that can be called to operate and control the peripherals such as the keyboard, text

display functions and so forth. In the IBM PC and AT, certain peripheral cards such as hard-

drive controllers and video display adapters carried their own BIOS extension ROM, which

provided additional functionality. Operating systems and executive software, designed to

supersede this basic firmware functionality, will provide replacement software interfaces to

applications.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

100www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 101: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

The term first appeared in the CP/M operating system, describing the part of CP/M loaded

during boot time that interfaced directly with the hardware (CP/M machines usually had a

simple boot loader in ROM, and nothing else). Most versions of DOS have a file called

"IBMBIO.COM" or "IO.SYS" that is analogous to the CP/M disk BIOS. The term was also

known as Binary Input/Output System and Basic Integrated Operating System. Among other

classes of computers, the generic terms boot monitor, boot loader or boot ROM were

commonly used. Some Sun and Macintosh PowerPC computers used Open Firmware for this

purpose. There are a few alternatives for Legacy BIOS in the x86 world: Extensible

Firmware Interface, Open Firmware (used on the OLPC XO-1) and coreboot.

2. IBM PC-compatible BIOS Chips

In principle, the BIOS in ROM was customized to the particular manufacturer's hardware,

allowing low-level services (such as reading a keystroke or writing a sector of data to

diskette) to be provided in a standardized way to to the operating system. For example, an

IBM PC might have had either a monochrome or a color display adapter, using different

display memory addresses and hardware - but the BIOS service to print a character on the

screen in text mode would be the same.

Prior to the early 1990s, BIOSes were stored in ROM or PROM chips, which could not be

altered by users. As its complexity and need for updates grew, and re-programmable parts

became more available, BIOS firmware was most commonly stored on EEPROM or flash

memory devices. According to Robert Braver, the president of the BIOS manufacturer Micro

Firmware, Flash BIOS chips became common around 1995 because the electrically erasable

PROM (EEPROM) chips are cheaper and easier to program than standard erasable PROM

(EPROM) chips. EPROM chips may be erased by prolonged exposure to ultraviolet light,

which accessed the chip via the window. Chip manufacturers use EPROM programmers

(blasters) to program EPROM chips. Electrically erasable (EEPROM) chips come with the

additional feature of allowing a BIOS reprogramming via higher-than-normal amounts of

voltage. BIOS versions are upgraded to take advantage of newer versions of hardware and to

correct bugs in previous revisions of BIOSes. The first flash chips attached to the ISA bus.

Starting in 1997, the BIOS flash moved to the LPC bus, a functional replacement for ISA,

following a new standard implementation known as "firmware hub" (FWH). Most BIOS

revisions created in 1995 and nearly all BIOS revisions in 1997 supported the year 2000. In

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

101www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 102: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

2006, the first systems supporting a Serial Peripheral Interface (SPI) appeared, and the BIOS

flash moved again.

The size of the BIOS, and the capacities of the ROM, EEPROM and other media it may be

stored on, has increased over time as new features have been added to the code; BIOS

versions now exist with sizes up to 8 megabytes. Some modern motherboards are including

even bigger NAND Flash ROM ICs on board which are capable of storing whole compact

operating system distribution like some Linux distributions. For example, some recent ASUS

motherboards included SplashTop Linux embedded into their NAND Flash ROM ICs

3. BIOS chip vulnerabilities

EEPROM chips are advantageous because they can be easily updated by the user; hardware

manufacturers frequently issue BIOS updates to upgrade their products, improve

compatibility and remove bugs. However, this advantage had the risk that an improperly

executed or aborted BIOS update could render the computer or device unusable. To avoid

these situations, more recent BIOSes use a "boot block"; a portion of the BIOS which runs

first and must be updated separately. This code verifies if the rest of the BIOS is intact (using

hash checksums or other methods) before transferring control to it. If the boot block detects

any corruption in the main BIOS, it will typically warn the user that a recovery process must

be initiated by booting from removable media (floppy, CD or USB memory) so the user can

try flashing the BIOS again. Some motherboards have a backup BIOS (sometimes referred to

as DualBIOS boards) to recover from BIOS corruptions. In 2007, Gigabyte began offering

motherboards with a QuadBIOS recovery feature.

There was at least one virus which was able to erase Flash ROM BIOS content, rendering

computer systems unusable.CIH, also known as "Chernobyl Virus", affected systems BIOS

and often they could not be fixed on their own since they were no longer able to boot at all.

To repair this, Flash ROM IC had to be ejected from the motherboard to be reprogrammed

somewhere else. Damage from the CIH virus was possible since most motherboards at the

time of CIH propagation used the same chip set, IntelTX, and most common operating

systems such as Windows 95 allowed direct hardware access to all programs.

Modern systems are not vulnerable to CIH because of a variety of chip sets being used which

are incompatible with the Intel TX chip set, and also other Flash ROM IC types. There is also

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

102www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 103: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

extra protection from accidental BIOS rewrites in the form of boot blocks which are protected

from accidental overwrite or dual and quad BIOS equipped systems which may, in the event

of a crash, use a backup BIOS. Also, all modern operating systems like Windows XP,

Windows Vista, Linux do not allow direct hardware access to user mode programs. So, as of

year 2008, CIH has become almost harmless and at most just bothers users by infecting

executable files without being able to cause any real harm, only triggering numerous virus

alerts from antivirus software.

4. Changing role of the BIOS

Some operating systems, for example MS-DOS, rely on the BIOS to carry out most

input/output tasks within the PC. A variety of technical reasons makes it inefficient for some

recent operating systems written for 32-bit CPUs such as Linux and Microsoft Windows to

invoke the BIOS directly. Larger, more powerful, servers and workstations using PowerPC or

SPARC CPUs by several manufacturers developed a platform-independent Open Firmware

(IEEE-1275), based on the Forth programming language. It is included with Sun's SPARC

computers, IBM's RS/6000 line, and other PowerPC CHRP motherboards. Later x86-based

personal computer operating systems, like Windows NT, use their own, native drivers which

also makes it much easier to extend support to new hardware, while the BIOS still relies on a

legacy 16-bit runtime interface. s such, the BIOS was relegated to bootstrapping, at which

point the operating system's own drivers can take control of the hardware.

There was a similar transition for the Apple Macintosh, where the system software originally

relied heavily on the ToolBoxa set of drivers and other useful routines stored in ROM based

on Motorola's 680x0 CPUs. These Apple ROMs were replaced by Open Firmware in the

PowerPC Macintosh, then EFI in Intel Macintosh computers.

Later BIOS took on more complex functions, by way of interfaces such as ACPI; these

functions include power management, hot swapping and thermal management. However

BIOS limitations (16-bit processor mode, only 1 MiB addressable space, PC AT hardware

dependencies, etc.) were seen as clearly unacceptable for the newer computer platforms.

Extensible Firmware Interface (EFI) is a specification which replaces the runtime interface of

the legacy BIOS. Initially written for the Itanium architecture, EFI is now available for x86

and x86-64 platforms; the specification development is driven by The Unified EFI Forum, an

industry Special Interest Group.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

103www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 104: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Linux has supported EFI via the elilo boot loader. The Open Source community increased

their effort to develop a replacement for proprietary BIOSes and their future incarnations

with an open sourced counterpart through the coreboot and OpenBIOS/Open Firmware

projects. AMD provided product specifications for some chipsets, and Google is sponsoring

the project. Motherboard manufacturer Tyan offers coreboot next to the standard BIOS with

their Opteron line of motherboards. MSI and Gigabyte have followed suit with the MSI

K9ND MS-9282 and MSI K9SD MS-9185 resp. the M57SLI-S4 models.

Topic : Recursion

Topic Objective:

At the end of this topic the student will be able to understand:

Recursive algorithms

Recursive programming

Binary search

Recursive data structures

Recursion versus iteration

Definition/Overview:

Definition: Recursion (computer science) is a way of thinking about and solving problems.

In fact, recursion is one of the central ideas of computer science. Solving a problem using

recursion means the solution depends on solutions to smaller instances of the same problem.

Most high-level computer programming languages support recursion by allowing a function

to call itself within the program text. Imperative languages define looping constructs like

while and for loops that are used to perform repetitive actions. Some functional programming

languages do not define any looping constructs but rely solely on recursion to repeatedly call

code. Computability theory has proven that these recursive only languages are

mathematically equivalent to the imperative languages, meaning they can solve the same

kinds of problems even without the typical control structures like while and for.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

104www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 105: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Key Points:

1. Recursive algorithms

A common method of simplification is to divide a problem into sub-problems of the same

type. This is known as dialecting. As a computer programming technique, this is called divide

and conquer, and it is key to the design of many important algorithms, as well as a

fundamental part of dynamic programming.

Virtually all programming languages in use today allow the direct specification of recursive

functions and procedures. When such a function is called, the computer (for most languages

on most stack-based architectures) or the language implementation keeps track of the various

instances of the function (on many architectures, by using a call stack, although other

methods may be used). Conversely, every recursive function can be transformed into an

iterative function by using a stack.

Most (but not all) functions and procedures that can be evaluated by a computer can be

expressed in terms of a recursive function (without having to use pure iteration), in

continuation-passing style; conversely any recursive function can be expressed in terms of

(pure) iteration, since recursion in itself is iterative too. In order to evaluate a function by

means of recursion, it has to be defined as a function of itself (e.g. the factorial n! = n * (n -

1)! , where 0! is defined as 1). Clearly thus, not all function evaluations lend itself for a

recursive approach. In general, all non-infinite functions can be described recursively

directly; infinite functions (e.g. the series for e = 1/1! + 2/2! + 3/3!...) need an extra 'stopping

criterium', e.g. the number of iterations, or the number of significant digits, because otherwise

recursive iteration would result in an endless loop.

To make a very literal example out of this: If an unknown word is seen in a book, the reader

can make a note of the current page number and put the note on a stack (which is empty so

far). The reader can then look the new word up and, while reading on the subject, may find

yet another unknown word. The page number of this word is also written down and put on

top of the stack. At some point an article is read that does not require any explanation. The

reader then returns to the previous page number and continues reading from there. This is

repeated, sequentially removing the topmost note from the stack. Finally, the reader returns to

the original book. This is a recursive approach.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

105www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 106: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Some languages designed for logic programming and functional programming provide

recursion as the only means of repetition directly available to the programmer. Such

languages generally make tail recursion as efficient as iteration, letting programmers express

other repetition structures (such as Scheme's map and for) in terms of recursion.

Recursion is deeply embedded in the theory of computation, with the theoretical equivalence

of μ-recursive functions and Turing machines at the foundation of ideas about the

universality of the modern computer.

2. Recursive programming

Creating a recursive procedure essentially requires defining a "base case", and then defining

rules to break down more complex cases into the base case. Key to a recursive procedure is

that with each recursive call, the problem domain must be reduced in such a way that

eventually the base case is arrived at.

Some authors classify recursion as either "generative" or "structural". The distinction is made

based on where the procedure gets the data that it works on. If the data comes from a data

structure like a list, then the procedure is "structurally recursive"; otherwise, it is

"generatively recursive.

3. Binary search

The binary search algorithm is a method of searching an ordered array for a single element by

cutting the array in half with each pass. The trick is to pick a midpoint near the center of the

array, compare the data at that point with the data being searched and then responding to one

of three possible conditions: the data is found, the data at the midpoint is greater than the data

being searched for, or the data at the midpoint is less than the data being searched for.

Recursion is used in this algorithm because with each pass a new array is created by cutting

the old one in half. The binary search procedure is then called recursively, this time on the

new (and smaller) array. Typically the array's size is adjusted by manipulating a beginning

and ending index. The algorithm exhibits a logarithmic order of growth because it essentially

divides the problem domain in half with each pass.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

106www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 107: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

4. Recursive data structures (structural recursion)

An important application of recursion in computer science is in defining dynamic data

structures such as Lists and Trees. Recursive data structures can dynamically grow to a

theoretically infinite size in response to runtime requirements; in contrast, a static array's size

requirements must be set at compile time.

5. Recursion versus iteration

In the "factorial" example the iterative implementation is likely to be slightly faster in

practice than the recursive one. This is almost definite for the Euclidean Algorithm

implementation. This result is typical, because iterative functions do not pay the "function-

call overhead" as many times as recursive functions, and that overhead is relatively high in

many languages. (Note that an even faster implementation for the factorial function on small

integers is to use a lookup table.)

There are other types of problems whose solutions are inherently recursive, because they

need to keep track of prior state. One example is tree traversal; others include the Ackermann

function and divide-and-conquer algorithms such as Quicksort. All of these algorithms can be

implemented iteratively with the help of a stack, but the need for the stack arguably nullifies

the advantages of the iterative solution.

Another possible reason for choosing an iterative rather than a recursive algorithm is that in

today's programming languages, the stack space available to a thread is often much less than

the space available in the heap, and recursive algorithms tend to require more stack space

than iterative algorithms. However, see the caveat below regarding the special case of tail

recursion.

Topic : Lists, Stacks, Queues, Trees, And Heaps

Topic Objective:

At the end of this topic the student will be able to understand:

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

107www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 108: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Lists

Stacks

Queue

Trees

Heaps

Definition/Overview:

Definition: In computer science, a list is an ordered collection of entities/items. In the context

of object-oriented programming languages, a list is defined as an instance of an abstract data

type (ADT), formalizing the concept of an ordered collection of entities. For example, an

ADT for untyped, mutable lists may be specified in terms of a constructor and four

operations: In computer science, a heap is a specialized tree-based data structure that satisfies

the heap property: if B is a child node of A, then key(A) ≥ key(B). This implies that an

element with the greatest key is always in the root node, and so such a heap is sometimes

called a max heap. (Alternatively, if the comparison is reversed, the smallest element is

always in the root node, which results in a min heap.) This is why heaps are used to

implement priority queues. The efficiency of heap operations is crucial in several graph

algorithms.

Key Points:

1. Lists

In practice, lists are usually implemented using arrays or linked lists of some sort; due to lists

sharing certain properties with arrays and linked lists. Informally, the term list is sometimes

used synonymously with linked list. A sequence is another name, emphasizing the ordering

and suggesting that it may not be a linked list.

There are two main ways to implement lists: linked lists (either singly or doubly-linked) and

dynamic arrays. See those articles for more information. In Lisp, lists are the fundamental

data type and can represent both program code and data. In most dialects, the list of the first

three prime numbers could be written as (list 2 3 5). In several dialects of Lisp, including

Scheme, a list is a collection of pairs, consisting of a value and a pointer to the next pair (or

null value), making a singly-linked list.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

108www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 109: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

The standard way of implementing lists, originating with Lisp, is to have each element of the

list contain both its value and a pointer indicating the location of the next element in the list.

This results in either a linked list or a tree, depending on whether the list has nested sublists.

However, some LISP implementations often use "compressed lists" which are arrays.

Some languages do not offer a list data structure, but offer the use of associative arrays or

some kind of table to emulate lists. For example, Lua provides tables. Although Lua stores

lists that have numerical indices as arrays internally, they still appear as hash tables. Some

languages implement lists using arrays.

Lists can be manipulated using iteration or recursion. The former is often preferred in non-

tail-recursive languages, and languages in which recursion over lists is for some other reason

uncomfortable. The latter is generally preferred in functional languages, since iteration is

associated with arrays and often regarded as imperative.

Because in computing, lists are easier to realize than sets, a finite set in mathematical sense

can be realized as a list with additional restrictions, that is, duplicate elements are disallowed

and such that order is irrelevant. If the list is sorted, it speeds up determining if a given item

is already in the set but in order to ensure the order, it requires more time to add new entry to

the list. In efficient implementations, however, sets are implemented using self-balancing

binary search trees or hash tables, rather than a list.

2. Stacks

In computer science, a stack is an abstract data type and data structure based on the principle

of Last In First Out (LIFO). Stacks are used extensively at every level of a modern computer

system. For example, a modern PC uses stacks at the architecture level, which are used in the

basic design of an operating system for interrupt handling and operating system function

calls. Among other uses, stacks are used to run a Java Virtual Machine, and the Java language

itself has a class called "Stack", which can be used by the programmer. The stack is

ubiquitous. A stack-based computer system is one that stores temporary information

primarily in stacks, rather than hardware CPU registers (a register-based computer system).

As an abstract data type, the stack is a container of nodes and has two basic operations: push

and pop. Push adds a given node to the top of the stack leaving previous nodes below. Pop

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

109www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 110: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

removes and returns the current top node of the stack. A frequently used metaphor is the idea

of a stack of plates in a spring loaded cafeteria stack. In such a stack, only the top plate is

visible and accessible to the user, all other plates remain hidden. As new plates are added,

each new plate becomes the top of the stack, hiding each plate below, pushing the stack of

plates down. As the top plate is removed from the stack, they can be used, the plates pop back

up, and the second plate becomes the top of the stack. Two important principles are

illustrated by this metaphor: the Last In First Out principle is one; the second is that the

contents of the stack are hidden. Only the top plate is visible, so to see what is on the third

plate, the first and second plates will have to be removed. This can also be written as FILO-

First In Last Out, i.e. the record inserted first will be popped out at last.

3. Queue

A queue (pronounced /kjuː/) is a particular kind of collection in which the entities in the

collection are kept in order and the principal (or only) operations on the collection are the

addition of entities to the rear terminal position and removal of entities from the front

terminal position. This makes the queue a First-In-First-Out (FIFO) data structure. In a FIFO

data structure, the first element added to the queue will be the first one to be removed. This is

equivalent to the requirement that whenever an element is added, all elements that were

added before have to be removed before the new element can be invoked. A queue is an

example of a linear data structure. Queues provide services in computer science, transport

and operations research where various entities such as data, objects, persons, or events are

stored and held to be processed later. In these contexts, the queue performs the function of a

buffer.

Queues are common in computer programs, where they are implemented as data structures

coupled with access routines, as an abstract data structure or in object-oriented languages as

classes. Common implementations are circular buffers and linked lists.

The defining attribute of a queue data structure is the fact that allows access to only the front

and back of the structure. Furthermore, elements can only be removed from the front and can

only be added to the back. In this way, an appropriate metaphor often used to represent

queues is the idea of a checkout line. Other examples of queues are people traveling up an

escalator, machine parts on an assembly line, or cars in line at a gas station. The recurring

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

110www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 111: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

theme is clear: queues are essentially the same as a queue you would get in a shop waiting to

pay.

In each of the cases, the customer or object at the front of the line was the first one to enter,

while at the end of the line is the last to have entered. Every time a customer finishes paying

for their items (or a person steps off the escalator, or the machine part is removed from the

assembly line, etc.) that object leaves the queue from the front. This represents the queue

dequeue function. Every time another object or customer enters the line to wait, they join the

end of the line and represent the enqueue function. The queue size function would return the

length of the line, and the empty function would return true only if there was nothing in the

line.

4. Trees

In computer science, a tree is a widely-used data structure that emulates a hierarchical tree

structure with a set of linked nodes. It is an acyclic connected graph where each node has a

set of zero or more children nodes, and at most one parent node.

A node may contain a value or a condition or represent a separate data structure or a tree of

its own. Each node in a tree has zero or more child nodes, which are below it in the tree (by

convention, trees grow down, not up as they do in nature). A node that has a child is called

the child's parent node (or ancestor node, or superior). A node has at most one parent.

The height of a node is the length of the longest downward path to a leaf from that node. The

height of the root is the height of the tree. The depth of a node is the length of the path to its

root (i.e., its root path). This is commonly needed in the manipulation of the various self

balancing trees, AVL Trees in particular. Conventionally, the value -1 corresponds to a

subtree with no nodes, whereas zero corresponds to a subtree with one node.

The topmost node in a tree is called the root node. Being the topmost node, the root node will

not have parents. It is the node at which operations on the tree commonly begin (although

some algorithms begin with the leaf nodes and work up ending at the root). All other nodes

can be reached from it by following edges or links. (In the formal definition, each such path

is also unique). In diagrams, it is typically drawn at the top. In some trees, such as heaps, the

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

111www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 112: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

root node has special properties. Every node in a tree can be seen as the root node of the

subtree rooted at that node.

Nodes at the bottommost level of the tree are called leaf nodes. Since they are at the

bottommost level, they do not have any children. They are also referred to as terminal nodes.

An internal node or inner node is any node of a tree that has child nodes and is thus not a leaf

node. A subtree is a portion of a tree data structure that can be viewed as a complete tree in

itself. Any node in a tree T, together with all the nodes below it, comprise a subtree of T. The

subtree corresponding to the root node is the entire tree; the subtree corresponding to any

other node is called is a proper subtree (in analogy to the term proper subset).

5. Heaps

Interestingly, full and almost full binary heaps may be represented using an array alone. The

first (or last) element will contain the root. The next two elements of the array contain its

children. The next four contain the four children of the two child nodes, etc. Thus the

children of the node at position n would be at positions 2n and 2n+1 in a one-based array, or

2n+1 and 2n+2 in a zero-based array. Balancing a heap is done by swapping elements which

are out of order. As we can build a heap from an array without requiring extra memory (for

the nodes, for example), heapsort can be used to sort an array in-place. One more advantage

of heaps over trees in some applications is that construction of heaps can be done in linear

time using Tarjan's algorithm.

Topic : Generics

Topic Objective:

At the end of this topic the student will be able to understand:

Introduction

Programming language support for generic programming

Definition/Overview:

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

112www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 113: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Definition: Generic programming is a style of computer programming in which algorithms

are written in terms of to-be-specified-later types that are then instantiated when needed for

specific types provided as parameters and was pioneered by Adawhich appeared in 1983.

This approach permits writing common functions or types that differ only in the set of types

on which they operate when used, thus reducing duplication. Software entities created using

generic programming are known as generics in Ada, Eiffel, Java, C#, Visual Basic .NET and

Haskell; templates in C++; and parameterized types in the influential 1994 book Design

Patterns. The authors of Design Patterns note that this technique, especially when combined

with delegation, is very powerful but that "Dynamic, highly parameterized software is harder

to understand than more static software.

Key Points:

1. Introduction

Generic programming refers to features of certain statically typed programming languages

that allow some code to effectively circumvent the static typing requirements. For instance in

C++, a template is a routine in which some parameters are qualified by a type variable. Since

code generation in C++ depends on concrete types, the template is specialized for each

combination of argument types that occur in practice. Generic programming is commonly

used to implement containers such as lists and hash tables and functions such as a particular

sorting algorithm for objects specified in terms more general than a concrete type.

2. Programming language support for generic programming

Generic programming facilities first appeared in the 1970s in languages like CLU and Ada,

and were subsequently adopted by many object-based and object-oriented languages,

including BETA, C++, D, Eiffel, Java, and DEC's now defunct Trellis-Owl language.

Implementations of generics in languages such as Java and C# are formally based on the

notion of parametricity, due to John C. Reynolds. Software entities created using generic

programming are known as generics in Ada, Eiffel, Java, C#, VB .NET and Haskell;

templates in C++; and parameterized types in Design Patterns.

Generic programming is implemented and supported differently within each language. The

term "generic" has also been used differently in programming contexts. For example, in Forth

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

113www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 114: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

the compiler can execute code while compiling and one can create new compiler keywords

and new implementations for those words on the fly. It has few words that expose the

compiler behaviour and therefore naturally offers generic programming capacities which,

however, are not referred to as such in most Forth texts. The term has been used in functional

programming, specifically in Haskell-like languages, which use a structural type system

where types are always parametric and the actual code on those types is generic. In these uses

generic programming still serves the similar purpose of code-saving and the rendering of an

abstraction.

However, templates are generally considered an improvement over macros for these

purposes. Templates are type-safe. Templates avoid some of the common errors found in

code that makes heavy use of function-like macros. Perhaps most importantly, templates were

designed to be applicable to much larger problems than macros.

There are three primary drawbacks to the use of templates: compiler support, poor error

messages, and code bloat. Many compilers historically have poor support for templates, thus

the use of templates can make code somewhat less portable. Support may also be poor when

a C++ compiler is being used with a linker which is not C++-aware, or when attempting to

use templates across shared library boundaries. Most modern compilers however now have

fairly robust and standard template support, and the new C++ standard, C++0x, is expected to

further address these issues.

Almost all compilers produce confusing, long, or sometimes unhelpful error messages when

errors are detected in code that uses templates. This can make templates difficult to develop.

Finally, the use of templates requires the compiler to generate a separate instance of the

templated class or function for every permutation of type parameters used with it. (This is

necessary because types in C++ are not all the same size, and the sizes of data fields are

important to how classes work.) So the indiscriminate use of templates can lead to code bloat,

resulting in excessively large executables. However, judicious use of template specialization

can dramatically reduce such code bloat in some cases. The extra instantiations generated by

templates can also cause debuggers to have difficulty working gracefully with templates. For

example, setting a debug breakpoint within a template from a source file may either miss

setting the breakpoint in the actual instantiation desired or may set a breakpoint in every

place the template is instantiated.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

114www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 115: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Also, because the compiler needs to perform macro-like expansions of templates and

generate different instances of them at compile time, the implementation source code for the

templated class or function must be available (e.g. included in a header) to the code using it.

Templated classes or functions, including much of the Standard Template Library (STL),

cannot be compiled. (This is in contrast to non-templated code, which may be compiled to

binary, providing only a declarations header file for code using it.) This may be a

disadvantage by exposing the implementing code, which removes some abstractions, and

could restrict its use in closed-source projects.

In Section 4 of this course you will cover these topics:Java Collections Framework

Java Collections Framework

Multithreading

Networking

Internationalization

Javabeans And Bean Events

Containers, Layout Managers, And Borders

Topic : Java Collections Framework

Topic Objective:

At the end of this topic the student will be able to understand:

Java collections framework

Automatic memory management

Definition/Overview:

Definition: Java is a programming language originally developed by James Gosling at Sun

Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform.

The language derives much of its syntax from C and C++ but has a simpler object model and

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

115www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 116: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

fewer low-level facilities. Java applications are typically compiled to bytecode that can run

on any Java virtual machine (JVM) regardless of computer architecture. The original and

reference implementation Java compilers, virtual machines, and class libraries were

developed by Sun from 1995. As of May 2007, in compliance with the specifications of the

Java Community Process, Sun made available most of their Java technologies as free

software under the GNU General Public License. Others have also developed alternative

implementations of these Sun technologies, such as the GNU Compiler for Java and GNU

Classpath.

Key Points:

1. Java collections framework

James Gosling initiated the Java language project in June 1991 for use in one of his many set-

top box projects. The language, initially called Oak after an oak tree that stood outside

Gosling's office, also went by the name Green and ended up later renamed as Java, from a list

of random words. Gosling aimed to implement a virtual machine and a language that had a

familiar C/C++ style of notation.

Sun released the first public implementation as Java 1.0 in 1995. It promised "Write Once,

Run Anywhere" (WORA), providing no-cost run-times on popular platforms. Fairly secure

and featuring configurable security, it allowed network- and file-access restrictions. Major

web browsers soon incorporated the ability to run secure Java applets within web pages, and

Java quickly became popular. With the advent of Java 2, new versions had multiple

configurations built for different types of platforms. For example, J2EE targeted enterprise

applications and the greatly stripped-down version J2ME for mobile applications. J2SE

designated the Standard Edition. In 2006, for marketing purposes, Sun renamed new J2

versions as Java EE, Java ME, and Java SE, respectively.

In 1997, Sun Microsystems approached the ISO/IEC JTC1 standards body and later the Ecma

International to formalize Java, but it soon withdrew from the process. Java remains a de

facto standard, controlled through the Java Community Process. At one time, Sun made most

of its Java implementations available without charge, despite their proprietary software

status. Sun generated revenue from Java through the selling of licenses for specialized

products such as the Java Enterprise System. Sun distinguishes between its Software

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

116www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 117: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Development Kit (SDK) and Runtime Environment (JRE) (a subset of the SDK); the primary

distinction involves the JRE's lack of the compiler, utility programs, and header files.

On 13 November 2006, Sun released much of Java as free and open source software under

the terms of the GNU General Public License (GPL). On 8 May 2007 Sun finished the

process, making all of Java's core code free and open-source, aside from a small portion of

code to which Sun did not hold the copyright

One characteristic of Java is portability, which means that computer programs written in the

Java language must run similarly on any supported hardware/operating-system platform. One

should be able to write a program once, compile it once, and run it anywhere.

This is achieved by compiling the Java language code, not to machine code but to Java

bytecode instructions analogous to machine code but intended to be interpreted by a virtual

machine (VM) written specifically for the host hardware. End-users commonly use a Java

Runtime Environment (JRE) installed on their own machine for standalone Java applications,

or in a Web browser for Java applets.

Standardized libraries provide a generic way to access host specific features such as graphics,

threading and networking. In some JVM versions, bytecode can be compiled to native code,

either before or during program execution, resulting in faster execution.

A major benefit of using bytecode is porting. However, the overhead of interpretation means

that interpreted programs almost always run more slowly than programs compiled to native

executables would, and Java suffered a reputation for poor performance. This gap has been

narrowed by a number of optimisation techniques introduced in the more recent JVM

implementations.

One such technique, known as just-in-time (JIT) compilation, translates Java bytecode into

native code the first time that code is executed, then caches it. This results in a program that

starts and executes faster than pure interpreted code can, at the cost of introducing occasional

compilation overhead during execution. More sophisticated VMs also use dynamic

recompilation, in which the VM analyzes the behavior of the running program and selectively

recompiles and optimizes parts of the program. Dynamic recompilation can achieve

optimizations superior to static compilation because the dynamic compiler can base

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

117www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 118: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

optimizations on knowledge about the runtime environment and the set of loaded classes, and

can identify hot spots - parts of the program, often inner loops, that take up the most

execution time. JIT compilation and dynamic recompilation allow Java programs to approach

the speed of native code without losing portability.

Another technique, commonly known as static compilation, or ahead-of-time (AOT)

compilation, is to compile directly into native code like a more traditional compiler. Static

Java compilers translate the Java source or bytecode to native object code. This achieves

good performance compared to interpretation, at the expense of portability; the output of

these compilers can only be run on a single architecture. AOT could give Java something

close to native performance, yet it is still not portable since there are no compiler directives,

and all the pointers are indirect with no way to micro manage garbage collection.

Java's performance has improved substantially since the early versions, and performance of

JIT compilers relative to native compilers has in some tests been shown to be quite similar.

The performance of the compilers does not necessarily indicate the performance of the

compiled code; only careful testing can reveal the true performance issues in any system.

One of the unique advantages of the concept of a runtime engine is that errors (exceptions)

should not 'crash' the system. Moreover, in runtime engine environments such as Java there

exist tools that attach to the runtime engine and every time that an exception of interest

occurs they record debugging information that existed in memory at the time the exception

was thrown (stack and heap values). These Automated Exception Handling tools provide

'root-cause' information for exceptions in Java programs that run in production, testing or

development environments.

2. Automatic memory management

Java uses an automatic garbage collector to manage memory in the object lifecycle. The

programmer determines when objects are created, and the Java runtime is responsible for

recovering the memory once objects are no longer in use. Once no references to an object

remain, the unreachable object becomes eligible to be freed automatically by the garbage

collector. Something similar to a memory leak may still occur if a programmer's code holds a

reference to an object that is no longer needed, typically when objects that are no longer

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

118www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 119: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

needed are stored in containers that are still in use. If a nonexistent object is called a "null

pointer exception" is thrown.

One of the ideas behind Java's automatic memory management model is that programmers be

spared the burden of having to perform manual memory management. In some languages

memory for the creation of objects is implicitly allocated on the stack, or explicitly allocated

and deallocated from the heap. Either way the responsibility of managing memory resides

with the programmer. If the program does not deallocate an object, a memory leak occurs. If

the program attempts to access or deallocate memory that has already been deallocated, the

result is undefined and the program may become unstable and/or may crash. This can be

partially remedied by the use of smart pointers, but it adds overhead and complexity.

Garbage collection is allowed to happen at any time. Ideally, it will occur when a program is

idle. It is guaranteed to occur if there is insufficient free memory on the heap to allocate a

new object, which can cause a program to stall momentarily. Where performance or response

time is important, explicit memory management and object pools are often used.

Java does not support C/C++ style pointer arithmetic, where object addresses and integers

(usually long integers) can be used interchangeably. This is to allow the garbage collector to

relocate referenced objects, and to ensure type safety and security. As in C++ and some other

object-oriented languages, variables of Java's primitive types are not objects. Values of

primitive types are either stored directly in fields (for objects) or on the stack (for methods)

rather than on the heap, as is the common case for objects (but see Escape analysis). This was

a conscious decision by Java's designers for performance reasons. Because of this, Java was

not considered to be a pure object-oriented programming language. However, as of Java 5.0,

autoboxing enables programmers to write as if primitive types are their wrapper classes, with

their object-oriented counterparts representing classes of their own, and freely interchange

between them for improved flexibility.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

119www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 120: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Topic : Java Collections Framework

Topic Objective:

At the end of this topic the student will be able to understand:

Introduction

Sorting Alogrithms

Definition/Overview:

Definition: In computer science and mathematics, a sorting algorithm is an algorithm that

puts elements of a list in a certain order. The most-used orders are numerical order and

lexicographical order. Efficient sorting is important to optimizing the use of other algorithms

(such as search and merge algorithms) that require sorted lists to work correctly; it is also

often useful for canonicalizing data and for producing human-readable output. More

formally, the output must satisfy two conditions:

o The output is in nondecreasing order (each element is no smaller than the previous

element according to the desired total order);

o The output is a permutation, or reordering, of the input.

Key Points:

1. Introduction

Since the dawn of computing, the sorting problem has attracted a great deal of research,

perhaps due to the complexity of solving it efficiently despite its simple, familiar statement.

For example, bubble sort was analyzed as early as 1956. Although many consider it a solved

problem, useful new sorting algorithms are still being invented (for example, library sort was

first published in 2004). Sorting algorithms are prevalent in introductory computer science

classes, where the abundance of algorithms for the problem provides a gentle introduction to

a variety of core algorithm concepts, such as big O notation, divide and conquer algorithms,

data structures, randomized algorithms, best, worst and average case analysis, time-space

tradeoffs, and lower bounds.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

120www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 121: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

2. Sorting algorithms

In this table, n is the number of records to be sorted. The columns "Average" and "Worst"

give the time complexity in each case, under the assumption that the length of each key is

constant, and that therefore all comparisons, swaps, and other needed operations can proceed

in constant time. "Memory" denotes the amount of auxiliary storage needed beyond that used

by the list itself, under the same assumption. These are all comparison sorts.

The following table describes sorting algorithms that are not comparison sorts. As such, they

are not limited by a lower bound. Complexities below are in terms of n, the number of items

to be sorted, k, the size of each key, and s, the chunk size used by the implementation. Many

of them are based on the assumption that the key size is large enough that all entries have

unique key values, and hence that n << 2k, where << means "much less than."

Topic : Multithreading

Topic Objective:

At the end of this topic the student will be able to understand:

Multithreading paradigm

Implementation specifics

Definition/Overview:

Definition: Multithreading computers have hardware support to efficiently execute multiple

threads. These are distinguished from multiprocessing systems (such as multi-core systems)

in that the threads have to share the resources of single core: the computing units, the CPU

caches and the translation lookaside buffer (TLB). Where multiprocessing systems include

multiple complete processing units, multithreading aims to increase utilization of a single

core by leveraging thread-level as well as instruction-level parallelism. As the two techniques

are complementary, they are sometimes combined in systems with multiple multithreading

CPUs and in CPUs with multiple multithreading cores.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

121www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 122: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Key Points:

1. Multithreading paradigm

The Multithreading paradigm has become more popular as efforts to further exploit

instruction level parallelism have stalled since the late-1990s. This allowed the concept of

Throughput Computing to re-emerge to prominence from the more specialized field of

transaction processing:

Even though it is very difficult to further speed up a single thread or single program, most

computer systems are actually multi-tasking among multiple threads or programs.

Techniques that would allow speed up of the overall system throughput of all tasks would be

a meaningful performance gain. The two major techniques for throughput computing are

multiprocessing and multithreading. Some advantages include:

If a thread gets a lot of cache misses, the other thread(s) can continue, taking advantage of the

unused computing resources, which thus can lead to faster overall execution, as these

resources would have been idle if only a single thread was executed.

If a thread can not use all the computing resources of the CPU (because instructions depend

on each other's result), running another thread permits to not leave these idle.

If several threads work on the same set of data, they can actually share its caching, leading to

better cache usage or synchronization on its values.

Some criticisms of multithreading include:

Multiple threads can interfere with each other when sharing hardware resources such as

caches or translation lookaside buffers (TLBs).

Execution times of a single-thread are not improved but can be degraded, even when only one

thread is executing. This is due to slower frequencies and/or additional pipeline stages that

are necessary to accommodate thread-switching hardware.

Hardware support for Multithreading is more visible to software, thus requiring more changes

to both application programs and operating systems than Multiprocessing.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

122www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 123: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

The mileage thus vary, Intel claims up to 30 percent benefits with its HyperThreading

technology , a synthetic program just performing a loop of non-optimized dependent floating-

point operations actually gets a 100 percent benefit when run in parallel. On the other hand,

assembly-tuned programs using e.g. MMX or altivec extensions and performing data pre-

fetches, such as good video encoders, do not suffer from cache misses or idle computing

resources, and thus do not benefit from hardware multithreading and can indeed see degraded

performance due to the contention on the shared resources. Hardware techniques used to

support multithreading often parallel the software techniques used for computer multitasking

of computer programs.

2. Implementation specifics

The simplest type of multi-threading is where one thread runs until it is blocked by an event

that normally would create a long latency stall. Such a stall might be a cache-miss that has to

access off-chip memory, which might take hundreds of CPU cycles for the data to return.

Instead of waiting for the stall to resolve, a threaded processor would switch execution to

another thread that was ready to run. Only when the data for the previous thread had arrived,

would the previous thread be placed back on the list of ready-to-run threads.

A major area of research is the thread scheduler which must quickly choose among the list of

ready-to-run threads to execute next as well as maintain the read-to-run and stalled thread

lists. An important sub-topic is the different thread priority schemes that can be used by the

scheduler. The thread scheduler might be implemented totally in software or totally in

hardware or as a hw/sw combination. Another area of research is what type of events should

cause a thread switch - cache misses, inter-thread communication, DMA completion, etc. If

the multithreading scheme replicates all software visible state, include privileged control

registers, TLBs, etc., then it enables virtual machines to be created for each thread. This

allows each thread to run its own operating system on the same processor. On the other hand,

if only user-mode state is saved, less hardware is required which would allow for more

threads to be active at one time for the same die-area/cost.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

123www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 124: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Topic : Networking

Topic Objective:

At the end of this topic the student will be able to understand:

Network classification

Types of networks

Basic hardware components

Definition/Overview:

Overview: A computer network is a group of interconnected computers. Networks may be

classified according to a wide variety of characteristics. This article provides a general

overview of some types and categories and also presents the basic components of a network.

Key Points:

1. Introduction

A network is a collection of computers and devices connected to each other. The network

allows computers to communicate with each other and share resources and information. The

Advance Research Projects Agency (ARPA) designed "Advanced Research Projects Agency

Network" (ARPANET) for the United States Department of Defense. It was the first

computer network in the world in late 1960's and early 1970's.

2. Network classification

The following list presents categories used for classifying networks.

2.1 Connection method

Computer networks can also be classified according to the hardware and software

technology that is used to interconnect the individual devices in the network, such as

Optical fiber, Ethernet, Wireless LAN, HomePNA, or Power line communication.

Ethernet uses physical wiring to connect devices. Frequently deployed devices

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

124www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 125: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

include hubs, switches, bridges and/or routers. Wireless LAN technology is designed

to connect devices without wiring. These devices use radio waves or infrared signals

as a transmission medium.

2.2 Scale

Based on their scale, networks can be classified as Local Area Network (LAN), Wide

Area Network (WAN), Metropolitan Area Network (MAN), Personal Area Network

(PAN), Virtual Private Network (VPN), Campus Area Network (CAN), Storage Area

Network (SAN), etc.

2.3 Functional relationship (network architecture)

Computer networks may be classified according to the functional relationships which

exist among the elements of the network, e.g., Active Networking, Client-server and

Peer-to-peer (workgroup) architecture.

2.4 Network topology

Computer networks may be classified according to the network topology upon which

the network is based, such as bus network, star network, ring network, mesh network,

star-bus network, tree or hierarchical topology network. Network topology signifies

the way in which devices in the network see their logical relations to one another. The

use of the term "logical" here is significant. That is, network topology is independent

of the "physical" layout of the network. Even if networked computers are physically

placed in a linear arrangement, if they are connected via a hub, the network has a Star

topology, rather than a bus topology. In this regard the visual and operational

characteristics of a network are distinct; the logical network topology is not

necessarily the same as the physical layout. Networks may be classified based on the

method of data used to convey the data, these include digital and analog networks.

3. Types of networks

Below is a list of the most common types of computer networks in order of scale.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

125www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 126: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

3.1 Personal area network

A personal area network (PAN) is a computer network used for communication

among computer devices close to one person. Some examples of devices that are used

in a PAN are printers, fax machines, telephones, PDAs and scanners. The reach of a

PAN is typically about 20-30 feet (approximately 6-9 meters), but this is expected to

increase with technology improvements.

3.2 Local area network

A local area network (LAN) is a computer network covering a small physical area,

like a home, office, or small group of buildings, such as a school, or an airport.

Current LANs are most likely to be based on Ethernet technology. For example, a

library may have a wired or wireless LAN for users to interconnect local devices (e.g.,

printers and servers) and to connect to the internet. On a wired LAN, PCs in the

library are typically connected by category 5 (Cat5) cable, running the IEEE 802.3

protocol through a system of interconnected devices and eventually connect to the

Internet. The cables to the servers are typically on Cat 5e enhanced cable, which will

support IEEE 802.3 at 1 Gbit/s. A wireless LAN may exist using a different IEEE

protocol, 802.11b, 802.11g or possibly 802.11n. The staff computers (bright green in

the figure) can get to the color printer, checkout records, and the academic network

and the Internet. All user computers can get to the Internet and the card catalog. Each

workgroup can get to its local printer. Note that the printers are not accessible from

outside their workgroup.

Typical library network, in a branching tree topology and controlled access to

resourcesAll interconnected devices must understand the network layer (layer 3),

because they are handling multiple subnets (the different colors). Those inside the

library, which have only 10/100 Mbit/s Ethernet connections to the user device and a

Gigabit Ethernet connection to the central router, could be called "layer 3 switches"

because they only have Ethernet interfaces and must understand IP. It would be more

correct to call them access routers, where the router at the top is a distribution router

that connects to the Internet and academic networks' customer access routers.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

126www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 127: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

The defining characteristics of LANs, in contrast to WANs (wide area networks),

include their higher data transfer rates, smaller geographic range, and lack of a need

for leased telecommunication lines. Current Ethernet or other IEEE 802.3 LAN

technologies operate at speeds up to 10 Gbit/s. This is the data transfer rate. IEEE has

projects investigating the standardization of 100 Gbit/s, and possibly 40 Gbit/s.

3.3 Campus area network

A campus area network (CAN) is a computer network made up of an interconnection

of local area networks (LANs) within a limited geographical area. It can be

considered one form of a metropolitan area network, specific to an academic setting.

In the case of a university campus-based campus area network, the network is likely

to link a variety of campus buildings including; academic departments, the university

library and student residence halls. A campus area network is larger than a local area

network but smaller than a wide area network (WAN) (in some cases).

The main aim of a campus area network is to facilitate students accessing internet and

university resources. This is a network that connects two or more LANs but that is

limited to a specific and contiguous geographical area such as a college campus,

industrial complex, office building, or a military base. A CAN may be considered a

type of MAN (metropolitan area network), but is generally limited to a smaller area

than a typical MAN. This term is most often used to discuss the implementation of

networks for a contiguous area. This should not be confused with a Controller Area

Network. A LAN connects network devices over a relatively short distance. A

networked office building, school, or home usually contains a single LAN, though

sometimes one building will contain a few small LANs (perhaps one per room), and

occasionally a LAN will span a group of nearby buildings. In TCP/IP networking, a

LAN is often but not always implemented as a single IP subnet.

3.4 Metropolitan area network

A metropolitan area network (MAN) is a network that connects two or more local

area networks or campus area networks together but does not extend beyond the

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

127www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 128: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

boundaries of the immediate town/city. Routers, switches and hubs are connected to

create a metropolitan area network.

3.5 Wide area network

A wide area network (WAN) is a computer network that covers a broad area (i.e., any

network whose communications links cross metropolitan, regional, or national

boundaries ). Less formally, a WAN is a network that uses routers and public

communications links . Contrast with personal area networks (PANs), local area

networks (LANs), campus area networks (CANs), or metropolitan area networks

(MANs) are usually limited to a room, building, campus or specific metropolitan area

(e.g., a city) respectively. The largest and most well-known example of a WAN is the

Internet. A WAN is a data communications network that covers a relatively broad

geographic area (i.e. one city to another and one country to another country) and that

often uses transmission facilities provided by common carriers, such as telephone

companies. WAN technologies generally function at the lower three layers of the OSI

reference model: the physical layer, the data link layer, and the network layer.

3.6 Global area network

A global area networks (GAN) specification is in development by several groups, and

there is no common definition. In general, however, a GAN is a model for supporting

mobile communications across an arbitrary number of wireless LANs, satellite

coverage areas, etc. The key challenge in mobile communications is "handing off" the

user communications from one local coverage area to the next. In IEEE Project 802,

this involves a succession of terrestrial WIRELESS local area networks (WLAN).

3.7 Virtual private network

A virtual private network (VPN) is a computer network in which some of the links

between nodes are carried by open connections or virtual circuits in some larger

network (e.g., the Internet) instead of by physical wires. The link-layer protocols of

the virtual network are said to be tunneled through the larger network when this is the

case. One common application is secure communications through the public Internet,

but a VPN need not have explicit security features, such as authentication or content

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

128www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 129: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

encryption. VPNs, for example, can be used to separate the traffic of different user

communities over an underlying network with strong security features. A VPN may

have best-effort performance, or may have a defined service level agreement (SLA)

between the VPN customer and the VPN service provider. Generally, a VPN has a

topology more complex than point-to-point. A VPN allows computer users to appear

to be editing from an IP address location other than the one which connects the actual

computer to the Internet.

3.8 Internetwork

A Internetworking involves connecting two or more distinct computer networks or

network segments via a common routing technology. The result is called an

internetwork (often shortened to internet). Two or more networks or network

segments connected using devices that operate at layer 3 (the 'network' layer) of the

OSI Basic Reference Model, such as a router. Any interconnection among or between

public, private, commercial, industrial, or governmental networks may also be defined

as an internetwork.

In modern practice, the interconnected networks use the Internet Protocol. There are

at least three variants of internetwork, depending on who administers and who

participates in them:

o Intranet

o Extranet

o Internet

Intranets and extranets may or may not have connections to the Internet. If connected

to the Internet, the intranet or extranet is normally protected from being accessed from

the Internet without proper authorization. The Internet is not considered to be a part of

the intranet or extranet, although it may serve as a portal for access to portions of an

extranet.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

129www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 130: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

3.9 Intranet

An intranet is a set of networks, using the Internet Protocol and IP-based tools such as

web browsers and file transfer applications, that is under the control of a single

administrative entity. That administrative entity closes the intranet to all but specific,

authorized users. Most commonly, an intranet is the internal network of an

organization. A large intranet will typically have at least one web server to provide

users with organizational information.

3.10 Extranet

An extranet is a network or internetwork that is limited in scope to a single

organization or entity but which also has limited connections to the networks of one

or more other usually, but not necessarily, trusted organizations or entities (e.g. a

company's customers may be given access to some part of its intranet creating in this

way an extranet, while at the same time the customers may not be considered 'trusted'

from a security standpoint). Technically, an extranet may also be categorized as a

CAN, MAN, WAN, or other type of network, although, by definition, an extranet

cannot consist of a single LAN; it must have at least one connection with an external

network.

3.11 Internet

The Internet is a specific internetwork. It consists of a worldwide interconnection of

governmental, academic, public, and private networks based upon the networking

technologies of the Internet Protocol Suite. It is the successor of the Advanced

Research Projects Agency Network (ARPANET) developed by DARPA of the U.S.

Department of Defense. The Internet is also the communications backbone underlying

the World Wide Web (WWW). The 'Internet' is most commonly spelled with a capital

'I' as a proper noun, for historical reasons and to distinguish it from other generic

internetworks. Participants in the Internet use a diverse array of methods of several

hundred documented, and often standardized, protocols compatible with the Internet

Protocol Suite and an addressing system (IP Addresses) administered by the Internet

Assigned Numbers Authority and address registries. Service providers and large

enterprises exchange information about the reachability of their address spaces

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

130www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 131: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

through the Border Gateway Protocol (BGP), forming a redundant worldwide mesh of

transmission paths.

4. Basic hardware components

All networks are made up of basic hardware building blocks to interconnect network nodes,

such as Network Interface Cards (NICs), Bridges, Hubs, Switches, and Routers. In addition,

some method of connecting these building blocks is required, usually in the form of galvanic

cable (most commonly Category 5 cable). Less common are microwave links (as in IEEE

802.12) or optical cable ("optical fiber"). An ethernet card may also be required.

4.1 Network interface cards

A network card, network adapter or NIC (network interface card) is a piece of

computer hardware designed to allow computers to communicate over a computer

network. It provides physical access to a networking medium and often provides a

low-level addressing system through the use of MAC addresses. It allows users to

connect to each other either by using cables or wirelessly.The NIC provides the

transfer of data in megabytes.

4.2 Repeaters

A repeater is an electronic device that receives a signal and retransmits it at a higher

power level, or to the other side of an obstruction, so that the signal can cover longer

distances without degradation. In most twisted pair ethernet configurations, repeaters

are required for cable runs longer than 100 meters away from the computer

4.3 Hubs

A hub contains multiple ports. When a packet arrives at one port, it is copied

unmodified to all ports of the hub for transmission. The destination address in the

frame is not changed to a broadcast address

4.4 Bridges

A network bridge connects multiple network segments at the data link layer (layer 2)

of the OSI model. Bridges do not promiscuously copy traffic to all ports, as hubs do,

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

131www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 132: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

but learn which MAC addresses are reachable through specific ports. Once the bridge

associates a port and an address, it will send traffic for that address only to that port.

Bridges do send broadcasts to all ports except the one on which the broadcast was

received.

Bridges learn the association of ports and addresses by examining the source address

of frames that it sees on various ports. Once a frame arrives through a port, its source

address is stored and the bridge assumes that MAC address is associated with that

port. The first time that a previously unknown destination address is seen, the bridge

will forward the frame to all ports other than the one on which the frame arrived.

Bridges come in three basic types:

o Local bridges: Directly connect local area networks (LANs)

o Remote bridges: Can be used to create a wide area network (WAN) link

between LANs. Remote bridges, where the connecting link is slower than the

end networks, largely have been replaced by routers.

o Wireless bridges: Can be used to join LANs or connect remote stations to

LANs.

4.5 Switches

A switch is a device that forwards and filters OSI layer 2 datagrams (chunk of data

communication) between ports (connected cables) based on the MAC addresses in the

packets. This is distinct from a hub in that it only forwards the packets to the ports

involved in the communications rather than all ports connected. Strictly speaking, a

switch is not capable of routing traffic based on IP address (OSI Layer 3) which is

necessary for communicating between network segments or within a large or complex

LAN. Some switches are capable of routing based on IP addresses but are still called

switches as a marketing term. A switch normally has numerous ports, with the

intention being that most or all of the network is connected directly to the switch, or

another switch that is in turn connected to a switch.

Switch is a marketing term that encompasses routers and bridges, as well as devices

that may distribute traffic on load or by application content (e.g., a Web URL

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

132www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 133: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

identifier). Switches may operate at one or more OSI model layers, including

physical, data link, network, or transport (i.e., end-to-end). A device that operates

simultaneously at more than one of these layers is called a multilayer switch.

Overemphasizing the ill-defined term "switch" often leads to confusion when first

trying to understand networking. Many experienced network designers and operators

recommend starting with the logic of devices dealing with only one protocol level, not

all of which are covered by OSI. Multilayer device selection is an advanced topic that

may lead to selecting particular implementations, but multilayer switching is simply

not a real-world design concept.

4.6 Routers

Routers are networking devices that forward data packets between networks using

headers and forwarding tables to determine the best path to forward the packets.

Routers work at the network layer

Topic : Internationalization

Topic Objective:

At the end of this topic the student will be able to understand:

Practice

Difficulties

Cost vs benefit tradeoff

Definition/Overview:

Overview: In computing, internationalization and localization (also spelled

internationalisation and localisation, see spelling differences) are means of adapting computer

software to different languages and regional differences. Internationalization is the process of

designing a software application so that it can be adapted to various languages and regions

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

133www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 134: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

without engineering changes. Localization is the process of adapting software for a specific

region or language by adding locale-specific components and translating text. Due to their

length, the terms are frequently abbreviated to the numeronyms i18n (where 18 stands for the

number of letters between the i and the n in internationalization, a usage coined at DEC in the

1970s or 80s) and L10n respectively. The capital L on L10n helps to distinguish it from the

lowercase i in i18n. Some companies, like Microsoft and IBM, use the term globalization for

the combination of internationalization and localization. Globalization can also be

abbreviated to g11n.

Key Points:

1. Practice

The current prevailing practice is for applications to place text in resource strings which are

loaded during program execution as needed. These strings, stored in resource files, are

relatively easy to translate. Programs are often built to reference resource libraries depending

on the selected locale data. One software library that aids this is gettext.

Thus to get an application to support multiple languages one would design the application to

select the relevant language resource file at runtime. Resource files are translated to the

required languages. This method tends to be application-specific and at best, vendor-specific.

The code required to manage date entry verification and many other locale-sensitive data

types also must support differing locale requirements. Modern development systems and

operating systems include sophisticated libraries for international support of these types.

2. Difficulties

While translating existing text to other languages may seem easy, it is more difficult to

maintain the parallel versions of texts throughout the life of the product. For instance, if a

message displayed to the user is modified, all of the translated versions must be changed.

This in turn results in somewhat longer development cycle. Many localization issues (e.g.

writing direction, text sorting) require more profound changes in the software than text

translation. For example, OpenOffice.Org achieves this with compilation switches.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

134www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 135: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

To some degree (e.g. for Quality assurance), the development team needs someone who

understands foreign languages and cultures and has a technical background. In large societies

with one dominant language/culture, it may be difficult to find such a person.

3. Cost vs benefit tradeoff

In a commercial setting, the benefit from localization is access to more markets. Some argue

that the commercial case to localize products into multiple languages is very obvious, and

that all is needed is a budgetary commitment from the producer to finance the considerable

costs. It costs more to produce products for international markets, but in an increasingly

global economy, supporting only one language/market is scarcely an option. Still, proprietary

software localization is impacted by economically viability and usually lacks the ability for

end users and volunteers to self-localize as is often the case in open-source environments.

Since open source software can generally be freely modified and redistributed, it is more

prone to internationalization. The KDE project, for example, has been translated into over

100 languages.

Topic : Javabeans And Bean Events

Topic Objective:

At the end of this topic the student will be able to understand:

JavaBean conventions

Adoption

GUI widget

Definition/Overview:

Overview: JavaBeans are reusable software components for Java that can be manipulated

visually in a builder tool. Practically, they are classes written in the Java programming

language conforming to a particular convention. They are used to encapsulate many objects

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

135www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 136: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

into a single object (the bean), so that they can be passed around as a single bean object

instead of as multiple individual objects. In layman's terms a JavaBean is a POJO that is

serializable, has a no-argument constructor, and allows access to properties using getter and

setter methods.

Key Points:

1. JavaBean conventions

In order to function as a JavaBean class, an object class must obey certain conventions about

method naming, construction, and behavior. These conventions make it possible to have tools

that can use, reuse, replace, and connect JavaBeans. The required conventions are:

The class must have a public default constructor. This allows easy instantiation within editing

and activation frameworks.

The class properties must be accessible using get, set, and other methods (so-called accessor

methods and mutator methods), following a standard naming convention. This allows easy

automated inspection and updating of bean state within frameworks, many of which include

custom editors for various types of properties.

The class should be serializable. This allows applications and frameworks to reliably save,

store, and restore the bean's state in fashion that is independent of the VM and platform.

Because these requirements are largely expressed as conventions rather than by implementing

interfaces, some developers view JavaBeans as Plain Old Java Objects that follow specific

naming conventions.

2. Adoption

AWT, Swing, and SWT, the major Java GUI toolkits, use JavaBeans conventions for their

components. This allows GUI editors like the Eclipse Visual Editor or the NetBeans GUI

Editor to maintain a hierarchy of components and to provide access to their properties via

uniformly-named accessors and mutators.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

136www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 137: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

3. GUI widget

In computer programming, a widget (or control) is an element of a graphical user interface

(GUI) that displays an information arrangement changeable by the user, such as a window or

a text box. The defining characteristic of a widget is to provide a single interaction point for

the direct manipulation of a given kind of data. Widgets are basic visual building blocks

which, combined in an application, hold all the data processed by the application and the

available interactions on this data.

A family of common reusable widgets has evolved for holding general information based on

the PARC research for the Xerox Alto User Interface. Different implementations of these

generic widgets are often packaged together in widget toolkits, which programmers use to

build graphical user interfaces (GUIs). Most operating systems include a set of ready-to-tailor

widgets that a programmer can incorporate in an application, specifying how it is to behave.

Each type of widgets generally is defined as a class by object-oriented programming (OOP).

Therefore, many widgets are derived from class inheritance.

Widgets are sometimes qualified as virtual to distinguish them from their physical

counterparts, e.g. virtual buttons that can be clicked with a mouse cursor, vs. physical buttons

that can be pressed with a finger.

A related (but different) concept is the desktop widget, a small specialized GUI application

that provides some visual information and/or easy access to frequently used functions such as

clocks, calendars, news aggregators, calculators and desktop notes. These kinds of widgets

are hosted by a widget engine.

Topic : Containers, Layout Managers, And Borders

Topic Objective:

At the end of this topic the student will be able to understand:

Containers

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

137www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 138: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Layout managers

Border

Definition/Overview:

Overview: In computer science, a container is a class, a data structure, or an abstract data

type (ADT) whose instances are collections of other objects. They are used to store objects in

an organized way following specific access rules. Layout managers are software components

used in widget toolkits which have the ability to lay out widgets by their relative positions

without using distance units. It is often more natural to define component layouts in this

manner than to define their position in pixels or common distance units, so a number of

popular widget toolkits include this ability by default. Widget toolkits that provide this

function can generally be classified into two groups: Borders define geographic boundaries of

political entities or legal jurisdictions, such as governments, states or subnational

administrative divisions. They may foster the setting up of buffer zones. Some borders are

fully or partially controlled, and may be crossed legally only at designated border

checkpoints.

Key Points:

1. Containers

Generally, container classes are expected to implement methods to do the following:

create a new empty container (constructor),

report the number of objects it stores (size),

delete all the objects in the container (clear),

insert new objects into the container,

remove objects from it,

provide access to the stored objects.

There are two types of containers: value containers and reference containers. Value based

containers store copies of the objects. Accessing an object also returns a copy of it.

Modifying an external object after it has been inserted in the container will not affect the

content of the container. Reference based containers only store pointers or references to the

objects. Accessing an object returns a reference to it. Modifying an external object after it has

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

138www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 139: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

been inserted in the container could result in modifying the content of the container (or more

precisely, the object stored in the container).

1.1 Containers in Object-Oriented programming

In object-oriented programming, a container class is any class that is capable of

storing other objects. Container classes usually implement some kind of data

structure, such as a list, map, set, array, or tree. A container class is usually able to

store an arbitrary number of data items, i.e. the size of the collection is adjusted

automatically.

1.2 Graphic Containers

Widget toolkits use special widgets also called Containers to group the other widgets

together (windows, panels, ...). Apart from their graphical properties, they have the

same type of behavior as container classes, as they keep a list of their child widgets,

and allow to add, remove, or retrieve widgets amongst their children.

2. Layout managers

Layout managers are software components used in widget toolkits which have the ability to

lay out widgets by their relative positions without using distance units. It is often more

natural to define component layouts in this manner than to define their position in pixels or

common distance units, so a number of popular widget toolkits include this ability by default.

Widget toolkits that provide this function can generally be classified into two groups:

Those where the layout behavior is coded in special graphic containers. This is the case in

XUL and the .NET Framework widget toolkit (both in Windows Forms and in XAML).

Those where the layout behavior is coded in layout managers, that can be applied to any

graphic container. This is the case in the Swing widget toolkit that is part of the Java API.

3. Border

In the past many borders were not clearly defined lines, but were neutral zones called

marchlands. This has been reflected in recent times with the neutral zones that were set up

along part ofSaudi Arabia's borders with Kuwait and Iraq (however, these zones no longer

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

139www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 140: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

exist). In modern times the concept of a marchland has been replaced by that of the clearly

defined and demarcated border. For the purposes of border control, airports and seaports are

also classed as borders. Most countries have some form of border control to restrict or limit

the movement of people, animals, plants, and goods into or out of the country. Under

international law, each country is generally permitted to define the conditions which have to

be met by a person to legally cross its borders by its own laws, and to prevent persons from

crossing its border when this happens in violation of those laws.

In order to cross borders, the presentation of passports and visas or other appropriate forms of

identity document is required by some legal orders. To stay or work within a country's

borders aliens (foreign persons) may need special immigration documents or permits that

authorise them to do so.

Moving goods across a border often requires the payment of excise tax, often collected by

customs officials. Animals (and occasionally humans) moving across borders may need to go

into quarantine to prevent the spread of exotic or infectious diseases. Most countries prohibit

carrying illegal drugs or endangered animals across their borders. Moving goods, animals or

people illegally across a border, without declaring them, seeking permission, or deliberately

evading official inspection constitutes smuggling.

3.1 Border economics

The presence of borders often fosters certain economic features or anomalies.

Wherever two jurisdictions come into contact, special economic opportunities arise

for border trade. Smuggling provides a classic case; contrariwise, a border region may

flourish on the provision of excise or of importexport services legal or quasi-legal,

corrupt or corruption-free. Different regulations on either side of a border may

encourage services to position themselves at or near that border: thus the provision of

pornography, of prostitution, of alcohol and/or of narcotics may cluster around

borders, city limits, county lines, ports and airports. In a more planned and official

context, Special Economic Zones (SEZs) often tend to cluster near borders or ports.

Human economic traffic across borders (apart from kidnapping), may involve mass

commuting between workplaces and residential settlements. The removal of internal

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

140www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 141: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

barriers to commerce, as in France after the French Revolution or in Europe since the

1940s, de-emphasises border-based economic activity and fosters free trade.

3.2 Border politics

Political borders have a variety of meanings for those whom they affect. Many

borders in the world have checkpoints where border control agents inspect those

crossing the boundary.

In much of Europe, such controls were abolished by the Schengen Agreement and

subsequent European Union legislation. Since the Treaty of Amsterdam, the

competence to pass laws on crossing internal and external boders within the European

Union and the associated Schengen States (Iceland, Norway, Switzerland, and

Liechtenstein) lies exclusively within the jurisdiction of the European Union, except

where states have used a specific right to opt-out (United Kingdom and Ireland, which

maintain a common travel area amongst themselves). For details, see Schengen

Agreement.

The United States has notably increased measures taken in border control on the

CanadaUnited States border and the United StatesMexico border during its War on

Terrorism. The 3600-km (2000-mile) US-Mexico border is probably "the world's

longest boundary between a First World and Third World country."

Historic borders such as the Great Wall of China, the Maginot Line, and Hadrian's

Wall have played a great many roles and been marked in different ways. While the

stone walls, the Great Wall of China and the Roman Hadrian's Wall in Britain had

military functions, the entirety of the Roman borders were very porous, a policy

which encouraged Roman economic activity with its neighbors. On the other hand, a

border like the Maginot Line was entirely military and was meant to prevent any

access in what was to be World War II to France by its neighbor, Germany.

3.3 Border studies

There has been a renaissance in the study of borders during the past two decades,

partially resulting from the creation of a counter narrative to notions of a borderless

world which have been advanced as part of globalization theory. Examples of recent

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

141www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 142: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

initiatives are the Border Regions in Transition network of scholars, the International

Boundaries Research Unit at the University of Durham, the Association of Borderland

Scholars in theUSA, and the founding of smaller border research centres at Nijmegen

and Queens University(Belfast).

In Section 5 of this course you will cover these topics:Menus, Toolbars, Dialogs, And Internal Frames

Mvc And Swing Models

Java Database Programming

Advanced Java Database Programming

Servlets

Javaserver Pages

Remote Method Invocation

Topic : Menus, Toolbars, Dialogs, And Internal Frames

Topic Objective:

At the end of this topic the student will be able to understand:

Introduction

Internal Frames for outdoor activities

Definition/Overview:

Overview: The internal frame backpack is a recent innovation, invented in 1967 by Greg

Lowe, who went on to found Lowepro, a company specializing in backpacks and other

carrying solutions for various equipment. An internal-frame pack has a large cloth section in

which a small frame is integrated. This frame generally consists of strips of either metal or

plastic that mold to one's back to provide a good fit, sometimes with additional metal stays to

reinforce the frame. Usually a complex series of straps works with the frame to distribute the

weight and hold it in place.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

142www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 143: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Key Points:

1. Introduction

The close fitting of the back section to the wearer's back allows the pack to be closely

attached to the body, and gives a predictable movement of the load; on the downside, the

tight fit reduces ventilation, so these type of packs tend to be more sweaty compared to

external frame packs. The internal construction also allows for a large storage compartment.

Internal-frame packs may provide a few lash points (including webbing loops and straps for

sleeping bags and other large items), but as the frame is fully integrated and not available on

the outside, it is difficult to lash a large, heavy item so that it stays fixed and does not bounce,

so most cargo must fit inside. Internal-frame packs originally suffered from smaller load

capacity and less comfortable fit during steady walking, but newer models have improved

greatly in these respects. In addition, because of their snug fit, they ride better in activities

that involve upper-body movement such as scrambling over rocky surfaces and skiing. The

improved internal frame models have largely replaced external frame backpacks for many

activities.

2. Internal Frames for outdoor activities

One common special type of backpack (sometimes referred to as a "technical pack" or "frame

pack") is designed for backpacking and other outdoors activities. These type of packs are

more complex than most other backpacks. Compared to backpacks used for more day-to-day

purposes such as schoolbooks, such packs are designed to carry substantially heavier loads,

and as a result most such packs attach not only at the shoulders but at the hips, using a padded

hip belt to distribute the majority of the weight of the pack to the legs and not the back. The

often heavily padded and sometimes semi-rigid shoulder straps are mainly for balancing the

weight. They usually (except for those used in ultralight backpacking) have a metal or plastic

frame to support and distribute the weight of the pack. Larger packs of this type tend to have

a subdivided main compartment. These trekking packs often have several pockets on the

outside; they may also have lash points on the exterior (either directly attached to the frame

or webbing loops), so that bulky items may be strapped on, although depending on the pack

design and type of trek most backpackers will try to stuff everything into the pack. Multiday

packs typically have a content between 60 and 100 liters (and are about 3ft /1 meter tall).

Smaller packs with similar features are available for shorter trips.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

143www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 144: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

The most common materials for such packs are canvas and nylon, either ripstop fabric for

lightweight packs or heavier fabric such as cordura for more typical usage. Most such packs

are purpose-designed for the outdoors market; however, it is not uncommon for military

surplus packing gear to be sold to outdoorspeople as well for the same purpose. The cheaper

versions of the outdoor packs are often favoured by city trekkers; as they have a large volume

and still carry relatively easily.

Outdoors packs, in addition to the distinction between external-frame and internal-frame, can

be further subdivided based on the duration of trip a pack might be expected to be used on;

daypacks hold supplies for a single day's hiking (size about 20-30 litres), while "weekender"

bags can hold two to three day's worth of gear and supplies (sizes about 40-50 litres). Larger

packs generally have no specific names but are designed to distribute the weight of increased

numbers of gear and supplies for longer-duration trips (60-100 litres); such packs often

include complex ergonomic support features to simplify the carrying of large amounts of

weight. A third type with little or no frame at all, similar to the bookbags used by students

and made of light fabric (often nylon ripstop, as mentioned above), is used in ultralight

backpacking to eliminate the weight of the frame and heavy fabric used in more typical

outdoors packs. Despite (or perhaps because of) their lesser weight, such packs are seldom

less expensive than more typical, regular-weight packs.

In addition, outdoors packs are designed for specific purposes such as kayaking/canoeing,

rock climbing, mountaineering, cross country skiing, and other such activities. Packs used in

competitive strategic sports such as paintball and airsoft are often based on or actually are

military gear.

Topic : Mvc And Swing Models

Topic Objective:

At the end of this topic the student will be able to understand:

Introduction

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

144www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 145: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Architecture

Debugging

Definition/Overview:

Overview: Swing is a widget toolkit for Java. It is part of Sun Microsystems' Java

Foundation Classes (JFC) an API for providing a graphical user interface (GUI) for Java

programs. Swing was developed to provide a more sophisticated set of GUI components than

the earlier Abstract Window Toolkit. Swing provides a native look and feel that emulates the

look and feel of several platforms, and also supports a pluggable look and feel that allows

applications to have a look and feel unrelated to the underlying platform.

Key Points:

1. Introduction

The Internet Foundation Classes (IFC) were a graphics library for Java originally developed

by Netscape Communications Corporation and first released on December 16, 1996. On April

2, 1997, Sun Microsystems and Netscape Communications Corporation announced their

intention to incorporate IFC with other technologies to form the Java Foundation Classes.

Swing introduced a mechanism that allowed the look and feel of every component in an

application to be altered without making substantial changes to the application code. The

introduction of support for a pluggable look and feel allows Swing components to emulate

the appearance of native components while still retaining the benefits of platform

independence. This feature also makes it easy to make an application written in Swing look

very different from native programs if desired.

Originally distributed as a separately downloadable library, Swing has been included as part

of the Java Standard Edition since release 1.2. The Swing classes and components are

contained in the javax.swing package hierarchy.

2. Architecture

Swing is a platform-independent, Model-View-Controller GUI framework for Java. It follows

a single-threaded programming model, and possesses the following traits:

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

145www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 146: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Swing is platform independent both in terms of its expression (Java) and its implementation

(non-native universal rendering of widgets).

Swing is a highly partitioned architecture, which allows for the "plugging" of various custom

implementations of specified framework interfaces: Users can provide their own custom

implementation(s) of these components to override the default implementations. In general,

Swing users can extend the framework by extending existing (framework) classes and/or

providing alternative implementations of core components.

Swing is a component-based framework. The distinction between objects and components is

a fairly subtle point: concisely, a component is a well-behaved object with a known/specified

characteristic pattern of behaviour. Swing objects asynchronously fire events, have "bound"

properties, and respond to a well-known set of commands (specific to the component.)

Specifically, Swing components are Java Beans components, compliant with the Java Beans

Component Architecture specifications.

Given the programmatic rendering model of the Swing framework, fine control over the

details of rendering of a component is possible in Swing. As a general pattern, the visual

representation of a Swing component is a composition of a standard set of elements, such as a

"border", "inset", decorations, etc. Typically, users will programmatically customize a

standard Swing component (such as a JTable) by assigning specific Borders, Colors,

Backgrounds, opacities, etc., as the properties of that component. The core component will

then use these property (settings) to determine the appropriate renderers to use in painting its

various aspects. However, it is also completely possible to create unique GUI controls with

highly customized visual representation.

Swing's heavy reliance on runtime mechanisms and indirect composition patterns allows it to

respond at runtime to fundamental changes in its settings. For example, a Swing-based

application can change its look and feel at runtime. Further, users can provide their own look

and feel implementation, which allows for uniform changes in the look and feel of existing

Swing applications without any programmatic change to the application code.

Swing's configurability is a result of a choice not to use the native host OS's GUI controls for

displaying itself. Swing "paints" its controls programmatically through the use of Java 2D

APIs, rather than calling into a native user interface toolkit. Thus, a Swing component does

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

146www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 147: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

not have a corresponding native OS GUI component, and is free to render itself in any way

that is possible with the underlying graphics APIs.

However, at its core every Swing component relies on an AWT container, since (Swing's)

JComponent extends (AWT's) Container. This allows Swing to plug into the host OS's GUI

management framework, including the crucial device/screen mappings and user interactions,

such as key presses or mouse movements. Swing simply "transposes" its own (OS agnostic)

semantics over the underlying (OS specific) components. So, for example, every Swing

component paints its rendition on the graphic device in response to a call to

component.paint(), which is defined in (AWT) Container. But unlike AWT components,

which delegated the painting to their OS-native "heavyweight" widget, Swing components

are responsible for their own rendering.

This transposition and decoupling is not merely visual, and extends to Swing's management

and application of its own OS-independent semantics for events fired within its component

containment hierarchies. Generally speaking, the Swing Architecture delegates the task of

mapping the various flavors of OS GUI semantics onto a simple, but generalized, pattern to

the AWT container. Building on that generalized platform, it establishes its own rich and

complex GUI semantics in the form of the JComponent model. A review of the source of

Container.java and JComponent.java classes is recommended for further insights into the

nature of the interface between Swing's lightweight components and AWT's heavyweight

widgets.

The Swing library makes heavy use of the Model/View/Controller software design pattern,

which conceptually decouples the data being viewed from the user interface controls through

which it is viewed. Because of this, most Swing components have associated models (which

are specified in terms of Java interfaces), and the programmer can use various default

implementations or provide their own. The framework provides default implementations of

model interfaces for all of its concrete components.

Typically, Swing component model objects are responsible for providing a concise interface

defining events fired, and accessible properties for the (conceptual) data model for use by the

associated JComponent. Given that the overall MVC pattern is a loosely-coupled

collaborative object relationship pattern, the model provides the programmatic means for

attaching event listeners to the data model object. Typically, these events are model centric

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

147www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 148: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

(ex: a "row inserted" event in a table model) and are mapped by the JComponent

specialization into a meaningful event for the GUI component.

The view component of a Swing JComponent is the object used to graphically "represent" the

conceptual GUI control. A distinction of Swing, as a GUI framework, is in its reliance on

programmatically-rendered GUI controls (as opposed to the use of the native host OS's GUI

controls). This distinction is a source of complications when mixing AWT controls, which

use native controls, with Swing controls in a GUI.

Finally, in terms of visual composition and management, Swing favors relative layouts

(which specify the positional relationships between components) as opposed to absolute

layouts (which specify the exact location and size of components). This bias towards "fluid"'

visual ordering is due to its origins in the applet operating environment that framed the design

and development of the original Java GUI toolkit. (Conceptually, this view of the layout

management is quite similar to that which informs the rendering of HTML content in

browsers, and addresses the same set of concerns that motivated the former.)

Swing allows one to specialize the look and feel of widgets, by modifying the default (via

runtime parameters), deriving from an existing one, by creating one from scratch, or,

beginning with J2SE 5.0, by using the skinnable synth Look and Feel (see Synth Look and

Feel), which is configured with an XML property file. The look and feel can be changed at

runtime, and early demonstrations of Swing frequently provided a way to do this.

Since early versions of Java, a portion of the Abstract Window Toolkit (AWT) has provided

platform-independent APIs for user interface components. In AWT, each component is

rendered and controlled by a native peer component specific to the underlying windowing

system.

By contrast, Swing components are often described as lightweight because they do not

require allocation of native resources in the operating system's windowing toolkit. The AWT

components are referred to as heavyweight components.

Much of the Swing API is generally a complementary extension of the AWT rather than a

direct replacement. In fact, every Swing lightweight interface ultimately exists within an

AWT heavyweight component because all of the top-level components in Swing (JApplet,

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

148www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 149: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

JDialog, JFrame, and JWindow) extend an AWT top-level container. However, the use of

both lightweight and heavyweight components within the same window is generally

discouraged due to Z-order incompatibilities.

The core rendering functionality used by Swing to draw its lightweight components is

provided by Java 2D, another part of JFC.

The Standard Widget Toolkit (SWT) is a competing toolkit originally developed by IBM and

now maintained by the Eclipse Foundation. SWT's implementation has more in common with

the heavyweight components of AWT. This confers benefits such as more accurate fidelity

with the underlying native windowing toolkit, at the cost of an increased exposure to the

native platform in the programming model.

The advent of SWT has given rise to a great deal of division among Java desktop developers,

with many strongly favoring either SWT or Swing. Sun's development on Swing continues to

focus on platform look and feel (PLAF) fidelity with each platform's windowing toolkit in the

approaching Java SE 7 release (as of December 2006[update]).

There has been significant debate and speculation about the performance of SWT versus

Swing; some hinted that SWT's heavy dependence on JNI would make it slower when the

GUI component and Java need to communicate data, but faster at rendering when the data

model has been loaded into the GUI. While Swing performs better the results greatly depend

on the context and the environments.

SWT serves the Windows platform very well but is considered by some to be less effective as

a technology for cross-platform development. By using the high-level features of each native

windowing toolkit, SWT returns to the issues seen in the mid 90's (with toolkits like zApp,

Zinc, XVT and IBM/Smalltalk) where toolkits attempted to mask differences in focus

behaviour, event triggering and graphical layout. Failure to match behavior on each platform

can cause subtle but difficult-to-resolve bugs that impact user interaction and the appearance

of the GUI.

3. Debugging

Swing application debugging can be difficult because of the toolkit's visual nature. In contrast

to non-visual applications, GUI applications cannot be as easily debugged using step-by-step

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

149www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 150: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

debuggers. One of the reasons is that Swing normally performs painting into an off-screen

buffer (double buffering) first and then copies the entire result to the screen. This makes it

impossible to observe the impact of each separate graphical operation on the user interface

using a general-purpose Java debugger. There are also some common problems related to the

painting thread. Swing uses the AWT event dispatching thread for painting components. In

accordance with Swing standards, all components must be accessed only from the AWT

event dispatch thread. If the application violates this rule, it may cause unpredictable

behaviour. If long-running operations are performed in the AWT event dispatch thread,

repainting of the Swing user interface temporary becomes impossible causing screen freezes.

Topic : Java Database Programming

Topic Objective:

At the end of this topic the student will be able to understand:

Introduction

Discussion

Debugging

Definition/Overview:

Overview: Java is a programming language originally developed by James Gosling at Sun

Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform.

The language derives much of its syntax from C and C++ but has a simpler object model and

fewer low-level facilities. Java applications are typically compiled to bytecode that can run

on any Java virtual machine (JVM) regardless of computer architecture.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

150www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 151: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Key Points:

1. Introduction

The original and reference implementation Java compilers, virtual machines, and class

libraries were developed by Sun from 1995. As of May 2007, in compliance with the

specifications of the Java Community Process, Sun made available most of their Java

technologies as free software under the GNU General Public License. Others have also

developed alternative implementations of these Sun technologies, such as the GNU Compiler

for Java and GNU Classpath.

One characteristic of Java is portability, which means that computer programs written in the

Java language must run similarly on any supported hardware/operating-system platform. One

should be able to write a program once, compile it once, and run it anywhere.

2. Discussion

This is achieved by compiling the Java language code, not to machine code but to Java

bytecode instructions analogous to machine code but intended to be interpreted by a virtual

machine (VM) written specifically for the host hardware. End-users commonly use a Java

Runtime Environment (JRE) installed on their own machine for standalone Java applications,

or in a Web browser for Java applets.

Standardized libraries provide a generic way to access host specific features such as graphics,

threading and networking. In some JVM versions, bytecode can be compiled to native code,

either before or during program execution, resulting in faster execution.

A major benefit of using bytecode is porting. However, the overhead of interpretation means

that interpreted programs almost always run more slowly than programs compiled to native

executables would, and Java suffered a reputation for poor performance. This gap has been

narrowed by a number of optimisation techniques introduced in the more recent JVM

implementations.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

151www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 152: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

3. Debugging

One such technique, known as just-in-time (JIT) compilation, translates Java bytecode into

native code the first time that code is executed, then caches it. This results in a program that

starts and executes faster than pure interpreted code can, at the cost of introducing occasional

compilation overhead during execution. More sophisticated VMs also use dynamic

recompilation, in which the VM analyzes the behavior of the running program and selectively

recompiles and optimizes parts of the program. Dynamic recompilation can achieve

optimizations superior to static compilation because the dynamic compiler can base

optimizations on knowledge about the runtime environment and the set of loaded classes, and

can identify hot spots - parts of the program, often inner loops, that take up the most

execution time. JIT compilation and dynamic recompilation allow Java programs to approach

the speed of native code without losing portability.

Another technique, commonly known as static compilation, or ahead-of-time (AOT)

compilation, is to compile directly into native code like a more traditional compiler. Static

Java compilers translate the Java source or bytecode to native object code. This achieves

good performance compared to interpretation, at the expense of portability; the output of

these compilers can only be run on a single architecture. AOT could give Java something

close to native performance, yet it is still not portable since there are no compiler directives,

and all the pointers are indirect with no way to micro manage garbage collection.

Java's performance has improved substantially since the early versions, and performance of

JIT compilers relative to native compilers has in some tests been shown to be quite similar.

The performance of the compilers does not necessarily indicate the performance of the

compiled code; only careful testing can reveal the true performance issues in any system.

One of the unique advantages of the concept of a runtime engine is that errors (exceptions)

should not 'crash' the system. Moreover, in runtime engine environments such as Java there

exist tools that attach to the runtime engine and every time that an exception of interest

occurs they record debugging information that existed in memory at the time the exception

was thrown (stack and heap values). These Automated Exception Handling tools provide

'root-cause' information for exceptions in Java programs that run in production, testing or

development environments.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

152www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 153: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Topic : Advanced Java Database Programming

Topic Objective:

At the end of this topic the student will be able to understand:

Introduction

History

Problems and patterns

Definition/Overview:

Overview: Object-oriented programming (OOP) is a programming paradigm that uses

"objects" and their interactions to design applications and computer programs. Programming

techniques may include features such as encapsulation, modularity, polymorphism, and

inheritance. It was not commonly used in mainstream software application development until

the early 1990s. Many modern programming languages now support OOP.

Key Points:

1. Introduction

Object-oriented programming can trace its roots to the 1960s. As hardware and software

became increasingly complex, quality was often compromised. Researchers studied ways to

maintain software quality and developed object-oriented programming in part to address

common problems by strongly emphasizing discrete, reusable units of programming logic.

The methodology focuses on data rather than processes, with programs composed of self-

sufficient modules (objects) each containing all the information needed to manipulate its own

data structure.

The Simula programming language was the first to introduce the concepts underlying object-

oriented programming (objects, classes, subclasses, virtual methods, coroutines, garbage

collection, and discrete event simulation) as a superset of Algol. Simula was used for physical

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

153www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 154: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

modeling, such as models to study and improve the movement of ships and their content

through cargo ports. Smalltalk was the first programming language to be called "object-

oriented".

OOP may be seen as a collection of cooperating objects, as opposed to the more conventional

model, in which a program is seen as a list of tasks (subroutines) to perform. In OOP, each

object is capable of receiving messages, processing data, and sending messages to other

objects.

Each object can be viewed as an independent machine with a distinct role or responsibility.

The actions (or "operators") on the objects are closely associated with the object. For

example, the data structures tend to carry their own operators around with them (or at least

"inherit" them from a similar object or class). The conventional approach tends to consider

data and behavior separately.

2. History

The concept of objects and instances in computing had its first major breakthrough with the

PDP-1 system at MIT which was probably the earliest example of capability based

architecture. Another early example was Sketchpad made by Ivan Sutherland in 1963;

however, this was an application and not a programming paradigm. Objects as programming

entities were introduced in the 1960s in Simula 67, a programming language designed for

making simulations, created by Ole-Johan Dahl and Kristen Nygaard of the Norwegian

Computing Centerin Oslo. (They were working on ship simulations, and were confounded by

the combinatorial explosion of how the different attributes from different ships could affect

one another. The idea occurred to group the different types of ships into different classes of

objects, each class of objects being responsible for defining its own data and behavior.) Such

an approach was a simple extrapolation of concepts earlier used in analog programming. On

analog computers, mapping from real-world phenomena/objects to analog phenomena/objects

(and conversely), was (and is) called 'simulation'. Simula not only introduced the notion of

classes, but also of instances of classes, which is probably the first explicit use of those

notions. The ideas of Simula 67 influenced many later languages, especially Smalltalk and

derivatives of Lisp and Pascal.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

154www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 155: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

The Smalltalk language, which was developed at Xerox PARC in the 1970s, introduced the

term object-oriented programming to represent the pervasive use of objects and messages as

the basis for computation. Smalltalk creators were influenced by the ideas introduced in

Simula 67, but Smalltalk was designed to be a fully dynamic system in which classes could

be created and modified dynamically rather than statically as in Simula 67. Smalltalk and

with it OOP were introduced to a wider audience by the August 1981 issue of Byte magazine.

In the 1970s, Kay's Smalltalk work had influenced the Lisp community to incorporate object-

based techniques which were introduced to developers via the Lisp machine. In the 1980s,

there were a few attempts to design processor architectures which included hardware support

for objects in memory but these were not successful. Examples include the Intel iAPX 432

and the Linn Smart Rekursiv.

Object-oriented programming developed as the dominant programming methodology during

the mid-1990s, largely due to the influence of C++. Its dominance was further enhanced by

the rising popularity of graphical user interfaces, for which object-oriented programming

seems to be well-suited. An example of a closely related dynamic GUI library and OOP

language can be found in the Cocoaframeworks on Mac OS X, written in Objective C, an

object-oriented, dynamic messaging extension to C based on Smalltalk. OOP toolkits also

enhanced the popularity of event-driven programming (although this concept is not limited to

OOP). Some feel that association with GUIs (real or perceived) was what propelled OOP into

the programming mainstream.

At ETH Zrich, Niklaus Wirth and his colleagues had also been investigating such topics as

data abstraction and modular programming. Modula-2 included both, and their succeeding

design, Oberon, included a distinctive approach to object orientation, classes, and such. The

approach is unlike Smalltalk, and very unlike C++.

Object-oriented features have been added to many existing languages during that time,

including Ada, BASIC, Fortran, Pascal, and others. Adding these features to languages that

were not initially designed for them often led to problems with compatibility and

maintainability of code.

In the past decade Java has emerged in wide use partially because of its similarity to C and to

C++, but perhaps more importantly because of its implementation using a virtual machine

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

155www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 156: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

that is intended to run code unchanged on many different platforms. This last feature has

made it very attractive to larger development shops with heterogeneous environments.

Microsoft's .NET initiative has a similar objective and includes/supports several new

languages, or variants of older ones, and also uses the idea of a virtual machine, which

enables it to run on other platforms besides Microsoft's (one implementation for Linux and

Mac OS X being the Mono Project).

More recently, a number of languages have emerged that are primarily object-oriented yet

compatible with procedural methodology, such as Python and Ruby. Probably the most

commercially important recent object-oriented languages are Visual Basic .NET (VB.NET)

and C#, both designed for Microsoft's .NET platform, and Java, developed by Sun

Microsystems. VB.NET and C# both support cross-language inheritance, allowing classes

defined in one language to subclass classes defined in the other language. Recently many

universities have begun to teach Object-oriented design in introductory computer science

classes.

Just as procedural programming led to refinements of techniques such as structured

programming, modern object-oriented software design methods include refinements such as

the use of design patterns, design by contract, and modeling languages (such as UML).

3. Problems and patterns

There are a number of programming challenges which a developer encounters regularly in

object-oriented design. There are also widely accepted solutions to these problems. The best

known are the design patterns codified by Gamma et al, but in a broader sense the term

"design patterns" can be used to refer to any general, repeatable solution to a commonly

occurring problem in software design. Some of these commonly occurring problems have

implications and solutions particular to object-oriented development.

3.1 Gang of Four design patterns

Design Patterns: Elements of Reusable Object-Oriented Software is an influential book

published in 1995 by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides,

sometimes casually called the "Gang of Four". Along with exploring the capabilities

and pitfalls of object-oriented programming, it describes 23 common programming

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

156www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 157: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

problems and patterns for solving them. As of April 2007, the book was in its 36th

printing.

3.2 Object-orientation and databases

Both object-oriented programming and relational database management systems

(RDBMSs) are extremely common in software today[update]. Since relational

databases don't store objects directly (though some RDBMSs have object-oriented

features to approximate this), there is a general need to bridge the two worlds. There are

a number of widely used solutions to this problem. One of the most common is object-

relational mapping, as found in libraries like Java Data Objects and Ruby on Rails'

ActiveRecord.

There are also object databases which can be used to replace RDBMSs, but these have

not been as commercially successful as RDBMSs.

Topic : Servlets

Topic Objective:

At the end of this topic the student will be able to understand:

Introduction

History

Servlet containers

Definition/Overview:

Overview: Servlets are Java programming language classes that dynamically process

requests and construct responses. The Java Servlet API allows a software developer to add

dynamic content to a Web server using the Java platform. The generated content is

commonly HTML, but may be other data such as XML. Servlets are the Java counterpart to

non-Java dynamic Web content technologies such as PHP, CGI and ASP.NET. Servlets can

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

157www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 158: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

maintain state across many server transactions by using HTTP cookies, session variables or

URL rewriting.

Key Points:

1. Introduction

A Servlet is an object that receives a request and generates a response based on that request.

The basic servlet package defines Java objects to represent servlet requests and responses, as

well as objects to reflect the servlet's configuration parameters and execution environment.

The package javax.servlet.http defines HTTP-specific subclasses of the generic servlet

elements, including session management objects that track multiple requests and responses

between the Web server and a client. Servlets may be packaged in a WAR file as a Web

application.

The Servlet API, contained in the Java package hierarchy javax.servlet, defines the expected

interactions of a Web container and a servlet. A Web container is essentially the component

of a Web server that interacts with the servlets. The Web container is responsible for

managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that

the URL requester has the correct access rights.

Servlets can be generated automatically by JavaServer Pages (JSP) compiler, or alternately

by template engines such as WebMacro. Often servlets are used in conjunction with JSPs in a

pattern called "Model 2", which is a flavor of the model-view-controller pattern.

2. History

The complete servlet specification was created by Sun Microsystems, with version 1.0

finalized in June 1997. Starting with version 2.3, the servlet specification was developed

under the Java Community Process. JSR 53 defined both the Servlet 2.3 and JavaServer Page

1.2 specifications. JSR 154 specifies the Servlet 2.4 and 2.5 specifications. As of May 10,

2006, the current version of the servlet specification is 2.5.

In his blog on java.net, Sun veteran and GlassFish lead Jim Driscoll details the history of

servlet technology. James Gosling first thought of servlets in the early days of Java, but the

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

158www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 159: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

concept did not become a product until Sun shipped the Java Web Server product. This was

before what is now the Java Platform, Enterprise Edition was made into a specification.

3. Servlet containers

A Servlet container is a specialized web server that supports Servlet execution. It combines

the basic functionality of a web server with certain Java/Servlet specific optimizations and

extensions such as an integrated Java runtime environment, and the ability to automatically

translate specific URLs into Servlet requests. Individual Servlets are registered with a Servlet

container, providing the container with information about what functionality they provide,

and what URL or other resource locator they will use to identify themselves. The Servlet

container is then able to initialize the Servlet as necessary and deliver requests to the Servlet

as they arrive. Many containers have the ability to dynamically add and remove Servlets from

the system, allowing new Servlets to quickly be deployed or removed without affecting other

Servlets running from the same container. Servlet containers are also referred to as web

containers or web engines. Like the other Java APIs, different vendors provide their own

implementation of the Servlet container standard. For a list of some of the free and

commercial web containers, see the list of Servlet containers. (Note that 'free' means that non-

commercial use is free. Some of the commercial containers, e.g. Resin and Orion, are free to

use in a server environment for non profit organizations).

Topic : Javaserver Pages

Topic Objective:

At the end of this topic the student will be able to understand:

JSP and Servlets

JSP Technology in the Java EE 5 Platform

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

159www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 160: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Definition/Overview:

Overview: JavaServer Pages (JSP) is a Java technology that allows software developers to

create dynamically-generated web sites, with HTML, XML, or other document types, in

response to a Web client request. The technology allows Java code and certain pre-defined

actions to be embedded into static content. The JSP syntax adds additional XML-like tags,

called JSP actions, to be used to invoke built-in functionality. Additionally, the technology

allows for the creation of JSP tag libraries that act as extensions to the standard HTML or

XML tags. Tag libraries provide a platform independent way of extending the capabilities of

a Web server. JSPs are compiled into Java Servlets by a JSP compiler. A JSP compiler may

generate a servlet in Java code that is then compiled by the Java compiler, or it may generate

byte code for the servlet directly. JSPs can also be interpreted on-the-fly, reducing the time

taken to reload changes.

Key Points:

1. JSP and Servlets

A Servlet is an object that receives a request and generates a response based on that request.

The basic servlet package defines Java objects to represent servlet requests and responses, as

well as objects to reflect the servlet's configuration parameters and execution environment.

The package javax.servlet.http defines HTTP-specific subclasses of the generic servlet

elements, including session management objects that track multiple requests and responses

between the Web server and a client. Servlets may be packaged in a WAR file as a Web

application.

Architecturally, JSP may be viewed as a high-level abstraction of servlets that is implemented

as an extension of the Servlet 2.1 API. Both servlets and JSPs were originally developed at

Sun Microsystems. Starting with version 1.2 of the JSP specification, JavaServer Pages have

been developed under the Java Community Process. JSR 53 defines both the JSP 1.2 and

Servlet 2.3 specifications and JSR 152 defines the JSP 2.0 specification. As of May 2006 the

JSP 2.1 specification has been released under JSR 245 as part of Java EE 5.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

160www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 161: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

2. JSP Technology in the Java EE 5 Platform

The focus of Java EE 5 has been ease of development by making use of Java language

annotations that were introduced by J2SE 5.0. JSP 2.1 supports this goal by defining

annotations for dependency injection on JSP tag handlers and context listeners.

Another key concern of the Java EE 5 specification has been the alignment of its webtier

technologies, namely JavaServer Pages (JSP), JavaServer Faces (JSF), and JavaServer Pages

Standard Tag Library (JSTL).

The outcome of this alignment effort has been the Unified Expression Language (EL), which

integrates the expression languages defined by JSP 2.0 and JSF 1.1.

The main key additions to the Unified EL that came out of the alignment work have been:

A pluggable API for resolving variable references into Java objects and for resolving the -

roperties applied to these Java objects, Support for deferred expressions, which may be

evaluated by a tag handler when needed, unlike their regular expression counterparts, which

get evaluated immediately when a page is executed and rendered, and Support for lvalue

expression, which appear on the left hand side of an assignment operation. When used as an

lvalue, an EL expression represents a reference to a data structure, for example: a JavaBeans

property, that is assigned some user input. The new Unified EL is defined in its own

specification document, which is delivered along with the JSP 2.1 specification. Thanks to

the Unified EL, JSTL tags, such as the JSTL iteration tags, can now be used with JSF

components in an intuitive way. JSP 2.1 leverages the Servlet 2.5 specification for its web

semantics

Topic : Remote Method Invocation

Topic Objective:

At the end of this topic the student will be able to understand:

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

161www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 162: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

Introduction to remote method invocation

Serializatio

Definition/Overview:

Overview: The Java Remote Method Invocation API, or Java RMI, is a Java application

programming interface for performing the object equivalent of remote procedure calls.

Key Points:

1. Introduction

There are two common implementations of the API. The original implementation depends on

Java Virtual Machine (JVM) class representation mechanisms and it thus only supports

making calls from one JVM to another. The protocol underlying this Java-only

implementation is known as Java Remote Method Protocol (JRMP). In order to support code

running in a non-JVM context, a CORBA version was later developed. Usage of the term

RMI may denote solely the programming interface or may signify both the API and JRMP,

whereas the term RMI-IIOP, read RMI over IIOP, denotes the RMI interface delegating most

of the functionality to the supporting CORBA implementation.

The original RMI API was generalized somewhat to support different implementations, such

as an HTTP transport. Additionally, work was done to CORBA, adding a pass by value

capability, to support the RMI interface. Still, the RMI-IIOP and JRMP implementations are

not fully identical in their interfaces.

The package name is java.rmi while most of Sun's implementation is located in the sun.rmi

package. Note that with Java versions before Java 5.0 it was necessary to compile RMI stubs

in a separate compilation step using rmic. Version 5.0 of Java and beyond no longer require

this step.

2. Serialization

Java provides automatic serialization which requires that the object be marked by

implementing the java.io.Serializable interface. Implementing the interface marks the class as

"okay to serialize," and Java then handles serialization internally. There are no serialization

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

162www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 163: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

methods defined on the Serializable interface, but a serializable class can optionally define

methods with certain special names and signatures that if defined, will be called as part of the

serialization/deserialization process. The language also allows the developer to override the

serialization process more thoroughly by implementing another interface, the Externalizable

interface, which includes two special methods that are used to save and restore the object's

state.

There are three primary reasons why objects are not serializable by default and must

implement the Serializable interface to access Java's serialization mechanism.

Not all objects capture useful semantics in a serialized state. For example, a Thread object is

tied to the state of the current JVM. There is no context in which a deserialized Thread object

would maintain useful semantics.

The serialized state of an object forms part of its class's compatibility contract. Maintaining

compatibility between versions of serializable classes requires additional effort and

consideration. Therefore, making a class serializable needs to be deliberate design decision

and not a default condition.

Serialization allows access to non-transient private members of a class that are not otherwise

accessible. Classes containing sensitive information (for example, a password) should not be

serializable or externalizable.

The standard encoding method uses a simple translation of the fields into a byte stream.

Primitives as well as non-transient, non-static referenced objects are encoded into the stream.

Each object that is referenced by the serialized object and not marked as transient must also

be serialized; and if any object in the complete graph of non-transient object references is not

serializable, then serialization will fail. The developer can influence this behavior by marking

objects as transient, or by redefining the serialization for an object so that some portion of the

reference graph is truncated and not serialized.

It is possible to serialize Java objects through JDBC and store them into a database.

While Swing components do implement the Serializable interface, they are not portable

between different versions of the Java Virtual Machine. As such, a Swing component, or any

component which inherits it, may be serialized to an array of bytes, but it is not guaranteed

that this storage will be readable on another machine.

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

163www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN

Page 164: figure, 75 percent were professional or work related, while the rest sold for personal or home use. About 81.5 percent of PCs shipped had been desktop computers, 16.4

www.bsscommunitycollege.in www.bssnewgeneration.in www.bsslifeskillscollege.in

164www.onlineeducation.bharatsevaksamaj.net www.bssskillmission.in

WWW.BSSVE.IN