Top Banner
CS20105: SE ‘E’ Principles of Programming Languages
168
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Ppl for students unit 1,2 and 3

C S 2 0 1 0 5 : S E ‘ E ’

Principles of Programming Languages

Page 2: Ppl for students unit 1,2 and 3

Course Structure

Unit 1

Introduction to Programming Languages

Unit 2

Imperative and Procedural Programming

Unit 3

Object Oriented Programming (Java)

Unit 4

Advanced Java

Unit 5

Case Studies of Programming Languages

Page 3: Ppl for students unit 1,2 and 3

Text Books

“Programming Languages Design and Implementation”

Pratt and Zelkowitz

“Java: The Complete Reference”

Herbert Schildt

Page 4: Ppl for students unit 1,2 and 3

What is a PL?

Vocabulary and set of grammatical rules for instructing a computer to perform specific tasks

An interface to interact with a computing machine

Widespread use began with FORTRAN in 1957

Types High Level – independent of underlying machine

Low Level

Middle Level

Special Purpose vs General Purpose Multi purpose – Java, Perl, Ruby, C++

Can be applied to a wide range of problems

Special purpose – Unix Shell, SQL, Latex

Page 5: Ppl for students unit 1,2 and 3

Programming Domains

Scientific: Heavily based on numerical algorithms (Fortran, C)

Business Applications: Storage, retrieval, and formatting of data, reporting. (COBOL, SQL)

Artificial Intelligence: Symbolic computing, List directed processing (LISP, Prolog)

Systems Programming: Fast, Low level features (C)

Internet: Web based programming (Perl, Java)

Simulation: Process modeling (MATLAB, GPSS)

Page 6: Ppl for students unit 1,2 and 3

Application Domains

Page 7: Ppl for students unit 1,2 and 3

Languages designed for specific purpose

LISP - Symbolic computation, automated reasoning

FP - Functional Programming, algebraic laws

BCPL – compiler writing

Simula - simulation

C – systems programming

ML – theorem proving

SmallTalk - Dynabook

Clu, SML Modules – modular programming

C++ - object orientation

Java – internet applications

Page 8: Ppl for students unit 1,2 and 3

Role of Programming Languages

Notations used for specifying, organizing and reasoning about computations

Providing ways of organizing computations to achieve the desired effect

Page 9: Ppl for students unit 1,2 and 3

Categories of Languages

Machine Language 0s and 1s Unintelligible “code” Unsuitable for programming

Assembly Language Names and symbols replace 0s and 1s Low Level More readable

High-Level Langauges Readable familiar notations Machine independence (portable) Availability of program libraries Consistency checks that can detect errors

Page 10: Ppl for students unit 1,2 and 3

Language Implementation

Compiler Translate the language down to the level of machine

Separate translation-time and run-time

More efficient

Interpreter Bring the machine up to the level of the language

Takes program and input together

Scans the program implementing operations as it encounters them, doing input/output as needed

More flexible

Can allow programs to be changed on the fly to add features or correct errors

Actual Practice combination of both

Page 11: Ppl for students unit 1,2 and 3

Why study Programming Languages?

Ability to develop effective algos

Cost of recursion in a language

Become a better software engineer

Ability to use a language better

Appreciate implementation issues

Better background for language selection

Familiar with range of languages

Understand issues / advantages / disadvantage

Increased capacity to express ideas Better vocabulary of programming constructs

Page 12: Ppl for students unit 1,2 and 3

Why study Programming Languages?

Ability to quickly learn new languages

Better understanding of implementation of concepts

How is “this feature” implemented?

Why does “this part” run so slowly?

Easier to design a new language

Page 13: Ppl for students unit 1,2 and 3

Pros and Cons

FORTRAN is a particularly good language for processing numerical data, but it does not lend itself very well to large business programs

Pascal is very good for writing well-structured and readable programs, but it is not as flexible as the C programming language

C++ embodies powerful object-oriented features, but it is complex and difficult to learn

Page 14: Ppl for students unit 1,2 and 3

Characteristics of a good programming language

Efficiency (cost of use)

program execution

program translation

program creation, testing and use

maintenance

Regularity

Generality

Orthogonality

Uniformity

Page 15: Ppl for students unit 1,2 and 3

Efficiency – cost of use

Chapter 3 Louden

15

The “first” goal (FORTRAN): execution efficiency

Still an important goal in some settings (C++, C)

Many other criteria can be interpreted from the point of view of efficiency: programming efficiency: writability or expressiveness (ability

to express complex processes and structures)

reliability (security).

maintenance efficiency: readability.

saw this as a goal for first time in Cobol

Page 16: Ppl for students unit 1,2 and 3

Other kinds of efficiency

Chapter 3 Louden

16

Efficiency of execution (optimizable)

Efficiency of translation. Are there features which are extremely difficult to check at compile time (or even run time)? e.g. Algol – prohibits assignment to dangling pointers

Implementability (cost of writing translator)

Cost of testing, maintenance

Page 17: Ppl for students unit 1,2 and 3

Features that aid efficiency of execution

Chapter 3 Louden

17

Static data types allow efficient allocation and access.

Manual memory management avoids overhead of “garbage collection”.

Simple semantics allow for simple structure of running programs

Page 18: Ppl for students unit 1,2 and 3

Note conflicts with efficiency

Chapter 3 Louden

18

Writability, expressiveness: no static data types (variables can hold anything, no need for type declarations). [harder to maintain]

Reliability, writability, readability: automatic memory management (no need for pointers). [runs slower]

Expressiveness, writability, readability: more complex semantics, allowing greater abstraction. [harder to translate]

Page 19: Ppl for students unit 1,2 and 3

Regularity – Consistency in Design

Chapter 3 Louden

19

Regularity is a measure of how well a language integrates its features, so that there are no unusual restrictions, interactions, or behavior

Makes it easy to remember

Regularity issues can often be placed in subcategories: Generality: are constructs general enough? (Or too

general?)

Orthogonality: are there strange interactions?

Uniformity: Do similar things look the same, and do different things look different?

Page 20: Ppl for students unit 1,2 and 3

Generality deficiencies

Chapter 3 Louden

20

In Pascal, procedures can be passed as parameters, but no procedure variable

Pascal has no variable length arrays –length is defined as part of definition (even when parameter)

Page 21: Ppl for students unit 1,2 and 3

Orthogonality: independence

Chapter 3 Louden

21

being able to combine various features of a language in all possible combinations, with every combination being meaningful eg. use of any expression in if()

Not context sensitive fewer exceptions and specia l cases to remember

Seems similar to “generality” but more of an “odd” decision rather than a limitation

For example, if I buy a sweater, I may have the following choices: short sleeve, long sleeve, or sleeveless small, medium, or large red, green, or blue

Page 22: Ppl for students unit 1,2 and 3

Examples of limitations

Chapter 3 Louden

22

If it is not possible to get sleeveless sweaters, that may be a lack of generality.

If any combination of any attributes can be used together, it is orthogonal.

Ability to combine various features effectively

If red sweaters cannot be purchased in a small size, but other sweaters can, it is non-orthogonal

Page 23: Ppl for students unit 1,2 and 3

Orthogonality

Chapter 3 Louden

23

o a relatively small set of primitive constructs can be combined in a relatively small number of ways. Every possible combination is legal.

o For example - in IBM assembly language there are different instructions for adding memory to register or register to register (non-orthogonal).

o In Vax, a single add instruction can have arbitrary operands.

o Closely related to simplicity - the more orthogonal, the fewer rules to remember.

Page 24: Ppl for students unit 1,2 and 3

Examples of non-orthogonality – C++

Chapter 3 Louden

24

We can convert from integer to float by simply assigning a float to an integer, but not vice versa. (not a question of ability to do – generality, but of the way it is done)

Arrays are pass by reference while integers are pass by value

A switch statement works with integers, characters, or enumerated types, but not doubles or Strings.

Page 25: Ppl for students unit 1,2 and 3

Non-regularity examples from C++

Chapter 3 Louden

25

Functions are not general: there are no local functions (simplicity of environment)

Declarations are not uniform: data declarations must be followed by a semicolon, function declarations must not

Lots of ways to increment – lack of uniformity (++i, i++, i = i+1)

i=j and i==j look the same, but are different

Lack of uniformity

Page 26: Ppl for students unit 1,2 and 3

What about Java?

Chapter 3 Louden

26

Are function declarations non-general?

There are no functions, so a non-issue. (Well, what about static methods?)

Are class declarations non-general?

No multiple inheritance (but there is a reason: complexity of environment).

Java has a good replacement: interface inheritance.

Do declarations require semicolons?

Local variables do, but is that an issue? (Not really - they look like statements.)

Page 27: Ppl for students unit 1,2 and 3

Java regularity, continued

Chapter 3 Louden

27

Are some parameters references, others not?

Yes: objects are references, simple data are copies.

This is a result of the non-uniformity of data in Java, in which not every piece of data is an object.

The reason is efficiency: simple data have fast access.

What is the worst non-regularity in Java?

My vote: arrays. But there are excuses.

Page 28: Ppl for students unit 1,2 and 3

Other design principles

Chapter 3 Louden

28

• Simplicity - make things as simple as possible, but not simpler (Einstein). (Pascal, C)

We can make things so simple that it doesn’t work well – no string handling, no reasonable I/0

Can be cumbersome to use or inefficient.

Simplicity of syntax, simplicity of concepts

Trade-off between “power” and “simplicity”

Page 29: Ppl for students unit 1,2 and 3

Other design principles

Chapter 3 Louden

29

• Expressiveness: make it possible to express conceptual abstractions directly and simply. (Scheme)

Helps you to think about the problem.

Perl, for example, allows you to return multiple arguments:

($a,$b) = swap($a,$b);

Support for abstraction

Page 30: Ppl for students unit 1,2 and 3

Other design principles

Chapter 3 Louden

30

Extensibility: allow the programmer to extend the language in various ways. (Scheme, C++)

Ability to modify with an intent of extending the power

Types, operators

Security: programs cannot do unexpected damage. (Java)

discourages errors

allows errors to be discovered

type checking

Page 31: Ppl for students unit 1,2 and 3

Other design principles

Chapter 3 Louden

31

Preciseness: having a definition that can answer programmers and implementors questions. (Most languages today, but only one has a mathematical definition: ML).

If it isn’t clear, there will be differences. Example: Declaration in local scope (for loop)

unknown/known after exit Example: implementation of switch statement Example: constants – expressions or not? Example: how much accuracy of float?

Page 32: Ppl for students unit 1,2 and 3

Other design principles

Chapter 3 Louden

32

Machine-independence: should run the same on any machine. (Java- big effort)

Consistent with accepted notations – easy to learn and understand for experienced programmers (Most languages today, but not Smalltalk & Perl)

Restrictability: a programmer can program effectively in a subset of the full language. (C++: avoids runtime penalties)

Naturalness: for the application intended

Portability : Pascal, JAVA-JVM making JAVA one of the most powerful language to use. Is C machine Independent or Dependent?

Page 33: Ppl for students unit 1,2 and 3

Is C portable?

C source code is portable if you have not entered into code for the underlying Machine.

But the executable code of C code is machine dependent

Also if your using turbo c (the old version), things like clrscr() and other crap won't be compatible.

C does not have strictness of programming constructs.

Eg: The size of Integer used in C language depends upon the underlying machine

What about Java?

Page 34: Ppl for students unit 1,2 and 3

Wikipedia moment:

Chapter 3 Louden

34

Syntactic sugar is a term coined by Peter J. Landin for additions to the syntax of a computer language that do not affect its expressiveness but make it "sweeter" for humans to use. Syntactic sugar gives the programmer (designer, in the case of specification computer languages) an alternative way of coding (specifying) that is more practical, either by being more succinct or more like some familiar notation.

Page 35: Ppl for students unit 1,2 and 3

Effects of environments on languages

Batch processing : Execution of Programs without Human Intervention

Most of the Languages cannot handle these constraints

OOP hardly support any requirements for BATCH Processing of JOBS.

Scripting languages

IBM’s JCL : run a batch job or start a subsystem

Page 36: Ppl for students unit 1,2 and 3

Effects of environments on languages

Interactive Environments : Software that runs on the input from Human Being

Writing Procedures for the Components that are already active

Visual programming language : Python, TCL

Interactive programming has also been used in applications that need to be rewritten without stopping them, a feature which the computer language Smalltalk is famous for

Page 37: Ppl for students unit 1,2 and 3

Effect of environments on languages

Embedded Environments : An embedded system is a computer system designed for specific control functions within a larger system often with real-time computing constraints.

HARDWARE + SOFTWARE INTEGRATION

C on Unix platform has been the most favorite for building embedded applications.

PERL, PYTHON has been recent entries in EP

Page 38: Ppl for students unit 1,2 and 3

Language design issues

Low-Level to High Level : Abstraction

Efficiency : Use of CPU

Memory

Underlying OS

Usability Ease of USE

Language Syntax

Functionality/Capability Stand Alone, WEB, Concurrency

Mobile Applications : JAVA and NOT C

System Programming

Page 39: Ppl for students unit 1,2 and 3

Language design issues

Readability

Coder’s experience v/s Language Implementation

Keywords : Print, Write Line

Coding style

Example : Enumerations, Inheritance, Type Checking

Design Patterns- OOP

Language extensibility

Allow to ADD new programming constructs

Exploit other languages

Page 40: Ppl for students unit 1,2 and 3

Goals of Language Design

Linear flow of control and powerful control structures

Makes debugging and verification easy

Abstraction

Scope and Binding as a technique which simplifies program verification and reduces programming errors caused by side effects

Comprehensible

Readability and maintainability

Page 41: Ppl for students unit 1,2 and 3

Goals of Language Design

Size of language as less as possible

Easier to implement

Easier to thoroughly understand the tool

Value of modular program structures

Trade offs among various possible features

Convenience vs efficiency

Page 42: Ppl for students unit 1,2 and 3

Major focus areas for language design

Data types and abstraction

# of pre-defined data types available

Means of combining primitive to give complex

Way in which new abstractions can be introduced

Control Structures

Means by which order of execution is determined

Restricted use of goto

Page 43: Ppl for students unit 1,2 and 3

Other Focus Areas

String processing and exception handling capabilities

Required by interactive systems and their use by non-programmers

Data management and more powerful input/output facilities

Development of conversational programs for accessing large databases

Program transferability through standardization

Page 44: Ppl for students unit 1,2 and 3

Programming Paradigms

How will you define Programming Paradigm ?

Its simply the STYLE of Computer Programming

Or the support/approach for problem-solving?

It depends upon you how you want to solve a particular problem, with what all considerations.

Example : Use of procedures/functions or set of statements one after other

Inheritance or from scratch

You want to play with system registers or data variables

Recursions or loops

Members of a given family differ in taste more than substance

Page 45: Ppl for students unit 1,2 and 3

Programming Paradigms

Imperative/Procedural/Operational

Declarative

Functional/Applicative

Logic/Rule-based

Object Oriented

Scripting

Concurrent

Page 46: Ppl for students unit 1,2 and 3

Imperative (How?)

PP which describes computation in terms of statements that change a program state.

Action oriented

Finite state machine computational model.

Assumes that the program maintains a modifiable store.

By changing the values of variables we alter what is stored, thus record state changes.

Mutable Data

Family representative: PASCAL and C

Page 47: Ppl for students unit 1,2 and 3

Imperative

Sequence of actions

Heavily based on von Neumann architecture

Variables, assignments and iterative repetitions

FORTRAN, ALGOL, PASCAL, C

Page 48: Ppl for students unit 1,2 and 3

Procedural

When imperative programming is combined with subprograms, it is called procedural programming

Obvious Problems

Solved using concept of Modules

Page 49: Ppl for students unit 1,2 and 3

Example

Page 50: Ppl for students unit 1,2 and 3

Object Oriented

Eliminate drawbacks of conventional programming methods by incorporating the best of structured programming features with several new concepts.

OOP allows us to decompose a problem into number of entities called objects and then build data and methods (functions) around these entities.

Structure programming: Top-Down v/s Bottom Up In OOPL emphasis is on DATA and its relationship with

the Functions. In OOPL data is not allowed to Freely flow throughout

the system. DATA is more safe and secure

Page 51: Ppl for students unit 1,2 and 3

Object Oriented

Emphasis is on data rather than procedure. WHAT and not HOW 1. Programs are divided into objects. 2. Data Structures are designed such that they characterize

the objects. 4 Methods that operate on the data of an object are tied

together in the data structure. 5 Data is hidden and can not be accessed by external

functions. 6 Objects may communicate with each other through

methods 7 Efficiency of imperative + Flexibility and reliability of

functional

Page 52: Ppl for students unit 1,2 and 3

Procedural vs. Object-Oriented

Procedural

Withdraw, deposit, transfer

Object Oriented

Customer, money,

account

How What

Page 53: Ppl for students unit 1,2 and 3

Procedural vs Object-Oriented

Emphasis on procedural abstraction.

Top-down design; Step-wise refinement.

Suited for programming in the small.

Easy to add new operations – only additive changes

Emphasis on data abstraction.

Bottom-up design; Reusable libraries.

Suited for programming in the large.

Easy to add new data representations – only additive changes

Page 54: Ppl for students unit 1,2 and 3

Functional (What?)

Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data.

FP maintains referential transparency.

Much easier to understand and predict the behaviour of a program

Avoids the use of Mutable data

The syntax has the form like:

functionn(…function2(function1 (data))…)

Page 55: Ppl for students unit 1,2 and 3

Example

A functional version (in Haskell) has a different feel to it: Fibonacci numbers, functional style -- describe an infinite list based on the recurrence

relation for Fibonacci numbers fibRecurrence first second = first : fibRecurrence

second (first + second) -- describe fibonacci list as fibRecurrence with initial

values 0 and 1 fibonacci = fibRecurrence 0 1 -- describe action to print the 10th element of the

fibonacci list main = print (fibonacci !! 10)

Page 56: Ppl for students unit 1,2 and 3

Quick Look

A programming language is a problem-solving tool.

Imperative style: program = algorithms + data

good for decomposition

Functional style: program = functions o functions

good for reasoning

Object-oriented style: program = objects + messages

good for modeling(!)

Other styles and paradigms: blackboard, pipes and filters,

constraints, lists, ...

Page 57: Ppl for students unit 1,2 and 3

Functional vs Imperative

Refer doc at C:\VIT\PPL\TE PPL\UNIT 1\TE PPL Notes

Page 58: Ppl for students unit 1,2 and 3

Procedural vs Functional

cs784(Prasad) L5Pdm

58

Program: a sequence of instructions for a von Neumann m/c.

Computation by instruction execution.

Iteration.

Modifiable or updateable variables.

Program: a collection of function definitions (m/c independent).

Computation by term rewriting.

Recursion.

Assign-only-once variables.

Page 59: Ppl for students unit 1,2 and 3

Logic

execute by checking for the presence of a certain enabling condition and, when present, executing an appropriate action The syntax has the form like: enabling condition1 action1

enabling condition2 action2

Enabling conditions determine the order of execution

Page 60: Ppl for students unit 1,2 and 3

Declarative Languages

Problem specification using functions or relations

Functional (apply functions to given parameters)

Logic (deductive reasoning, rule based)

Page 61: Ppl for students unit 1,2 and 3

Concurrent

Parallel execution of processes.

Multi-tasking or multi-threading primitives.

Inter process communication and synchronization.

Helps in speeding up the execution of parallel algorithms

Examples: Concurrent C, Java, Fortran-90

Page 62: Ppl for students unit 1,2 and 3

Self Study

Comparison of different programming paradigms

Page 63: Ppl for students unit 1,2 and 3

Imperative Languages

CRs PASCAL and C PASCAL designed as teaching language C designed as implementation language

Values of data can change as program runs Action statements

“programs” are not same as “computations” Static programs but dynamic computations While there is input, do something “invariants” relate the two

Structured control flow (evident from syntactic structure) Sequential statements Selection statements Iteration statements

Page 64: Ppl for students unit 1,2 and 3

Constants and Variables

Page 65: Ppl for students unit 1,2 and 3

Operators

Arithmetic

Logical

Relational

Associativity

Precedence

Difference between = and ==?

++ and --

Page 66: Ppl for students unit 1,2 and 3

Selection Statements

Control Statements / Branch Statements

IF-ELSE

Nested IF-ELSE

Conditional Expression

Switch statements

Page 67: Ppl for students unit 1,2 and 3

IF…ELSE

If (expression) Statement1

Else Statement2

Else is optional

Scope of if and scope of else

Non zero means true

Coding shortcuts (expression) vs (expression != 0)

Watch out for a trap!

Page 68: Ppl for students unit 1,2 and 3

Nested IF ELSE

Who does the “else” belong to?

If (n>=0)

For (i=0; i<n; i++)

If (s[i]>0) {

Printf(“something”);

Return I;

}

Else

printf( (“error: n is negative”);

Page 69: Ppl for students unit 1,2 and 3

ELSE-IF

Multi-way decision

If (expression) Statement

Else if (expression) Statement

...

Else Statement

Last else is optional

Improves efficiency – by skipping evaluation

Page 70: Ppl for students unit 1,2 and 3

SWITCH

Page 71: Ppl for students unit 1,2 and 3

Iteration Statements

Loop statements

Pre-test Condition is tested before each iteration

Post-test Condition is tested after each iteration

FOR Initializer

Loop condition

Incrementer

All 3 are optional: what about condition?

WHILE – has only loop condition

DO-WHILE

Page 72: Ppl for students unit 1,2 and 3

Test your skills

While (x != 3) {

i=i-1;

}

Can you write this using for?

Page 73: Ppl for students unit 1,2 and 3

Nested Loop

Page 74: Ppl for students unit 1,2 and 3

Jump Statements

Unconditional branch

GOTO label Transfer to statement marked with the label within the function

BREAK Exit from innermost for, while, do or switch statements

Control is transferred to statement immediately after the block in which break appears

CONTINUE Skip to next iteration of for, while or do construct

Control is transferred to statement beginning the block

RETURN

Page 75: Ppl for students unit 1,2 and 3

Data Types

Imperative programmers want the ability to manipulate the representation of data

Functional programmers like the ability to work with values independent of how they are stored

Primitive types held in machine locations First class citizens

Denoted by a name Can be the value of an expression Can appear on the right side of assignment Operations are built into the language

Constructed or structured types Why types are required? Data representation Storage classification Operator validation

Page 76: Ppl for students unit 1,2 and 3

Data Types in C

Page 77: Ppl for students unit 1,2 and 3

Type Checking

checking that each operation receives the proper number and type of arguments

dynamic vs static type checking

some languages do not have concept of declarations – such variables are called typeless

Strongly typed language

if all type errors can be detected statically in a program

every operation is type safe

Pure strong typed is rare, C is near strong type

Page 78: Ppl for students unit 1,2 and 3

Records/Structures

Allow to treat a group of related variables as a single unit Payroll record Struct point { Int x; Int y;

} “member” Struct {…} x,y,z; Struct point pt = {20, 300}; Pt.x, pt.y Structures can be nested Allowed operations: copy it, assign to it, &, .

Page 79: Ppl for students unit 1,2 and 3

Union

Variable that may hold (at different times) objects of different types and sizes

Allows manipulation of different kind of data in a single area of storage

Union u_tag { Int ival;

Float fval;

Char *sval;

} u;

U is large enough to hold the largest member

Programmer’s responsibility to keep track of what’s currently stored

Page 80: Ppl for students unit 1,2 and 3

Pointer

Another primitive type, just like int

Indirect addressing

How do “pointers” help?

Efficiency: Moving/copying a large data structure vs moving/copying a pointer to it

Dynamic data: implementing growable/shrinkable data structures

First class citizens

Pointer size is always fixed

Page 81: Ppl for students unit 1,2 and 3

Pointer operations

Indirection or dereferencing operator: *

int x=1;

Int *px;

Px = &x;

Y= *px + 1

(*px)++ vs *px++

Px = py

Page 82: Ppl for students unit 1,2 and 3

Reference

Special kind of pointer type in C++

Used primarily for formal parameters in function definitions

A constant pointer that is always implicitly dereferenced

int result = 0;

int &ref_result = result;

ref_result = 100;

two way communication between caller and callee can be done using pointer also, but that makes code less readable

and less safe

Page 83: Ppl for students unit 1,2 and 3

Dangling pointers

Dangling pointer

Pointing to storage being used for another purpose

Typically, the storage has been de-allocated

Int g(void) {

Int x=1;

Return &x;

}

Page 84: Ppl for students unit 1,2 and 3

Memory Leak

Storage that is allocated but is inaccessible is called garbage

Program that creates garbage over iterations is said to have memory leak

Pointer assignment can create garbage!

Page 85: Ppl for students unit 1,2 and 3

Procedural

Re-usable piece of code

Each execution of procedure body is called activation of body

A location can hold different values state changes through different computations

Three mappings:

Name to declaration

Declaration to location

Location to value

Page 86: Ppl for students unit 1,2 and 3

Benefits of Procedures

Procedure Abstraction

Focus on “what” instead of “how”

Implementation Hiding

Modular Programs

Libraries

Page 87: Ppl for students unit 1,2 and 3

Elements of a procedure

Name

Body

Formals

Placeholders for actuals

Result type (optional)

Page 88: Ppl for students unit 1,2 and 3

Blocks

Page 89: Ppl for students unit 1,2 and 3

Scope

Binding: mapping name occurrence to declaration

Occurrence of name is within the scope of declaration

The scope of a variable are the set rules which defines the

accessibility of the variables in a program or a block

Lifetime: Time for which it will be alive

Static Scoping – Variables can be bound at compile time without regards to calling code Also called lexical scoping

Dynamic Scoping – Variable binding (context) can only be determined at the moment code is executed

Page 90: Ppl for students unit 1,2 and 3

Local and Global Variables

Local recognized only within a single function

Global recognized in two or more functions

Page 91: Ppl for students unit 1,2 and 3

Storage Class

Two ways of characterizing variables

By data type

By storage class – permanence and scope

Where the variable will be stored

CPU registers or memory

Default initial value of the variable

Scope of the variable

Life of the variable

Page 92: Ppl for students unit 1,2 and 3

Automatic

Declared within the block and are local to the block

Lives as long as control is in that block

Default storage class Includes formal argument declarations

Memory is allocated automatically upon entry to a function and freed automatically upon exit from the function - stack

If explicitly initialized, it will be re-initialized each time

If not, the value will be garbage

Page 93: Ppl for students unit 1,2 and 3

Register

Stored in register Hence provide certain control over efficiency of the program

Variables which are used repeatedly or whose access times are critical may be declared to be of storage class register

Variables can be declared as a register as follows

Everything else remains the same as auto

Not guaranteed! Falls back to auto

Not every type can be stored! falls back to auto

Page 94: Ppl for students unit 1,2 and 3

Static

Static automatic variables continue to exist even after the block in which they are defined terminates.

Thus value is retained between function calls

Default initial value = 0

Scope is local but life is as long as the program lives

Initializer is executed only once

Do not get created on stack, but in a separate segment of memory called “data segment”

Page 95: Ppl for students unit 1,2 and 3

Extern

Scope: “global” Life: from point of definition through the remainder of

the program Defined outside of all functions Before or after, doesn’t matter However, if you have to use before defining, then declare once more

by using extern keyword

Variable defined in one file can be used in another by declaring as extern in the latter Best practice – include these in a header file and #include it

Default initial value = 0 Static variable can also be declared outside all functions Treated as extern, but scope limited to that file only

Page 96: Ppl for students unit 1,2 and 3

Procedure/Function Calls

Strict sense of the term

procedure => proper procedure

function => function procedure

procedure call

“using” a procedure

A function call pushes onto call Stack

A return from the function pops up the stack

Page 97: Ppl for students unit 1,2 and 3

Parameter Passing Methods

Matching of actuals with formals when a procedure call occurs

Two main types

Call by value

Call by reference

What is used in C/C++?

How then can we achieve two way communication?

Page 98: Ppl for students unit 1,2 and 3

Other Methods

call by name pure substitution, evaluation of actuals only when referenced

call by value-result final content of formal copied back into actual

call by constant value formal parameter acts as local constant during the execution of

procedure

call by result used only to transmit result back

initial value of actual parameter makes no difference and cannot be used

at termination, final value of formal parameter is assigned as new value of actual parameter

Page 99: Ppl for students unit 1,2 and 3

Activation Records

A declaration can be bound to a different location, each time the procedure is activated

Associated with each activation of a procedure is storage for the variables declared in the procedure

This is called an activation record

Name to declaration compile time

Declaration to location activation time

Location to value run time

Page 100: Ppl for students unit 1,2 and 3

Control flow between activations

Control can be in at most one activation of a procedure at a time

Procedure executes completely before returning control

LIFO manner

Activation Tree

Page 101: Ppl for students unit 1,2 and 3

Elements of Activation Record

Also called frame

local variables

formal parameters

Additional information needed for activation

Temporary variables

Control link or dynamic link

Points to activation record of runtime caller

Access link or static link

used to implement statically scoped languages

Not required in C

• Procedure within procedure not allowed

• Only two places to look for a declaration of a name – local or global

Page 102: Ppl for students unit 1,2 and 3

Recursion

Recursion is a programming technique that allows the programmer to express operations in terms of themselves

A procedure is activated again from within its own body

Each recursive activation needs its own activation record

Page 103: Ppl for students unit 1,2 and 3

A Problem!

int f(int n, int v) {

if (n == 0)

return v;

else

return f(n - 1, v + n);}

int main()

{

return f(1000000, 0);

}

STACK OVERFLOW

Page 104: Ppl for students unit 1,2 and 3

Stack Explained

The computer keeps function calls on a stack

Too many functions are called without ending, the program will crash.

A call stack is a stack data structure that stores information about the active subroutines of a computer program

Page 105: Ppl for students unit 1,2 and 3

How Does It Work?

Page 106: Ppl for students unit 1,2 and 3

How Does It Work?

Page 107: Ppl for students unit 1,2 and 3

Storage Management

Lifetime of an activation record From: allocation To: location can no longer be accessed from the program Typically tied to LIFO

Stack Natural use of stack (LIFO) Eg. C – obeys stack discipline Problem: if you need to access that location even after activation has ended Procedures cannot be used as parameters or results statically defined “Stack Frame”

Heap Storage for activation record allocated in heap Records stay as long as they are needed, even after control has returned Garbage collection Eg. JAVA

Page 108: Ppl for students unit 1,2 and 3

Static

Simplest of all

allocation during translation that remains fixed throughout execution

Retain values between activations – shared by all activations of a procedure

Recursion requires non-static variables

FORTRAN does not support recursion. Thus all variables an be treated as static

Page 109: Ppl for students unit 1,2 and 3

Memory layout for C programs

Program counter

Code does not change during execution

Static global data

Determined at compile time

Stack local data

Grows and shrinks as activations start and end

Heap dynamic data

Allocated and deallocated through library procedures

Page 110: Ppl for students unit 1,2 and 3

What happens when a C procedure is called

Caller evaluates actual parameters and places them on the activation record of the callee

State information is saved (control link)

Callee allocates space for its local variables

Callee allocates temporary storage for storing partial results during calculations

Body of callee is executed Additional activations may occur

Outgoing parameters, incoming for next frame

Control returns to the caller Stack is popped

Page 111: Ppl for students unit 1,2 and 3

Self Study

Structure

Generic Templates in C++

Library Classes in C++

Page 112: Ppl for students unit 1,2 and 3

Object Oriented Paradigm

ML no abstraction

AL some abstraction of underlying machine

Imperative abstractions of AL Require you to think in terms of structure of computer rather

than the structure of the problem you are trying to solve

Modeling machine

Alternative approach model the problem LISP all problems are lists

PROLOG all problems are chains of decisions

Java tools to represent the elements in problem space

C++ = Hybrid, Java = pure OO

Page 113: Ppl for students unit 1,2 and 3

Key Characteristics of SmallTalk

Everything is an object Fancy variable which can accept requests

Program is a bunch of objects telling each other what to do by sending messages Calling a method that belongs to a particular object

Each object has its own memory made up of other objects

Every object has a type Each object is an instance of a class

All objects of a particular type can receive same messages

Page 114: Ppl for students unit 1,2 and 3

114

An object represents an individual, identifiable item, unit, or

entity, either real or abstract, with a well-defined role in the

problem domain.

They are the basic runtime entities in the program around

which the entire set of data and functions are wrapped around.

114

What is an object?

Tangible Things as a car, printer, ...

Roles as employee, boss, ...

Incidents as flight, overflow, ...

Interactions as contract, sale, ...

Basic run-time unit

Page 115: Ppl for students unit 1,2 and 3

An Object has …

State Internal data called Fields

Guaranteed to be initialized

Behavior Methods

Identity Unique address somewhere identity

Page 116: Ppl for students unit 1,2 and 3

Classes

User defined Data type, Just as your

structures in C.

Objects are nothing but variables of Class Data-Type

Once you have defined a class, you can create any no. of

objects of that Class.

Example : Customer is a Class, and Cust1, Cust2, Cust3 are

instances of Customer Class.

A Class is thus a collection of Objects of similar behavior.

Basic program unit

Customer

Name

Address

Age

Account No.

Page 117: Ppl for students unit 1,2 and 3

Key Points

You manipulate objects with references

String s; only reference, not the object

You must create all the objects

String s = “abcd”

String s = new String(“abcd”);

Primitive types boolean, char, byte, short, int, long, float, double, void

no concept of “unsigned”

fixed sizes

Page 118: Ppl for students unit 1,2 and 3

Structure of a Java Program

Classes

import

package

comments

“main”

any number of main methods can be there

java.lang

File names

Compiling and running a Java program

Page 119: Ppl for students unit 1,2 and 3

Storage in Java?

Registers no direct control compiler does whatever is required

Stack fast and efficient less flexible compiler must know before hand exact size and lifetime of

all data because it must generate the code to move the stack pointer up and down

references are stored on stack

Heap dynamic compiler does not need to know how much or how long allocation takes more time

Static Constant values directly in program code Non RAM storage

Page 120: Ppl for students unit 1,2 and 3

An object has an Interface

Light

On, off, brighten, dim

Specifies which messages the object can accept

Implementation actual code to carry out the operation

Think of an object as “service provider”

Page 121: Ppl for students unit 1,2 and 3

Java Features

Scope

Ability of C/C++ to “hide” a variable in a larger scope is not there in Java

Java is a free-form language

Objects are available whenever you need them

{

String s = new String(“abcd”);

}

Saves programmer, but then requires a garbage collector

Eliminates memory leak

Page 122: Ppl for students unit 1,2 and 3

Constructors

Every object must be created

Storage is allocated and constructor is called

Name of constructor must match the name of class EXACTLY

In Java, creation and initialization are unified concepts

You can’t have one without the other

Constructors don’t return anything

Default constructors and Custom Constructors

Page 123: Ppl for students unit 1,2 and 3

Method Overloading

Using the same name for different purposes instead of different unique names for each

Wash

Shirt

Car

Dog

Method overloading is must for constructors

Each overloaded method must take a unique list of argument types

Number, type and order of arguments

Page 124: Ppl for students unit 1,2 and 3

Access Specifiers

For each field and method in a class

In C++ a specifier controls all defns following it until another access specifier comes along

Class creators and client programmers

Reasons for access control

To keep client programmers away from stuff they are not supposed to touch

Allow class creators to change internal implementation without worrying about how it is going to affect other consumers

Page 125: Ppl for students unit 1,2 and 3

Access Specifiers

public available to everyone

private can be accessed only from within that class compile time error otherwise

Accessors (getters) and mutators (setters)

protected within that class + inheriting classes

default package access

Public > protected > default > private

A class cannot be private or protected

Page 126: Ppl for students unit 1,2 and 3

static keyword

Normally you need an instance of a class to be able to do something meaningful

How about?

If you want shared storage for some piece of data

Method which isn’t associated with any object, but the whole class

For example, essential for defining main

Also called class data and class methods

Page 127: Ppl for students unit 1,2 and 3

this keyword

Only one method in a class

Yet a.f(1) and b.f(1) are different. How does the method know for which object it is being called?

Behind the scenes Banana.f(a,1);

Banana.f(b,1);

this keyword gives you the reference of the current object can be used only inside a method

Normally not required, but two imp uses distinguish formal with actual parameters

implementing chain of commands – example increment()

Page 128: Ppl for students unit 1,2 and 3

Calling constructors from constructors

this(argument-list)

calls another version of the constructor

Cannot be used inside non-constructors

Cannot call more than one constructor like this

Constructor call must be the first thing you do, otherwise error

Page 129: Ppl for students unit 1,2 and 3

this and static

No “this” for a static method

You cannot call non-static methods from inside static methods

static methods are like global functions

static is not object oriented!

Page 130: Ppl for students unit 1,2 and 3

Putting things together – birth of an object!

The first time an object of type Car is created or the first time a static method or field of Car is accessed, Java interpreter locates Car.class by searching through the classpath

Class is loaded, static initializers are run never again

when you do new Car(), first enough storage is allocated on heap

storage is wiped to zero any initializations at the point of field definition are

executed constructors are executed

Page 131: Ppl for students unit 1,2 and 3

Reusing classes

Can be done in two ways

composition

inheritance

Page 132: Ppl for students unit 1,2 and 3

Composition

A class made up of other classes

“has-a” relationship

a car has an engine

Concept of reusing the implementation

Simply place object references inside new classes

Page 133: Ppl for students unit 1,2 and 3

Inheritance

Concept of reusing the interface

base class, super class, parent class

derived class, inherited class, sub class

Shape Circle, Square, Rectangle

Automatically get all the fields and methods of base class

We always use inheritance “Object”

Page 134: Ppl for students unit 1,2 and 3

Inheritance

Inheritance creates new types

contains all members of base class

duplicates the interface of the base class

Two varieties

add new methods

change behavior of existing methods – “overriding”

sometimes you may want to do something and then call the base class method for the rest “super” keyword

Page 135: Ppl for students unit 1,2 and 3

is-a vs is-like-a

is-a

override only base class methods

derived type is exactly the same as base type

pure substitution

circle “is-a” shape

is-like-a

define new methods

“extending” the interface

new methods not accessible from base type

Page 136: Ppl for students unit 1,2 and 3

Overriding and hiding fields and methods

Upcasting and downcasting

Polymorphism

Page 137: Ppl for students unit 1,2 and 3

Constructors in derived classes

Inheritance doesn’t just copy the interface of the base class

An object of derived class contains within it a subobject of base class – as if wrapped

Java automatically inserts calls to the base class constructor in the derived-class constructor

Capable of handling only default constructors

Construction happens from base “outward”

If you want specific constructore to be called, use “super”

Page 138: Ppl for students unit 1,2 and 3

Types of Inheritance

Single Inheritance Only one direct base class

Multiple Inheritance More than one direct base class – not allowed in Java

Multi-Level Inheritance Base class in turn is also a derived class from some other base

class

Hierarchical Inheritance One base class and many derived classes

Hybrid Inheritance Combination: multiple + multi-level or multiple + hierarchical

Page 139: Ppl for students unit 1,2 and 3

Types of Inheritance

Public Inheritance Private Inheritance Protected Inheritence In a public inheritance, public and protected members of

the base class remain public and protected members of the derived class.

In a protected inheritance, public and protected members of the base class are protected members of the derived class.

In a private inheritance, public and protected members of the base class become private members of the derived class.

Page 140: Ppl for students unit 1,2 and 3

Composition vs Inheritance

Composition is more flexible

members are typically private thus allowing to change them without affecting the consumers

allows changing the member objects at run time to dynamically change the behavior of the program

Inheritance on the other hand must put compile time restrictions on classes created with inheritance

When you want features and not interface – use composition

Car doesn’t contain a vehicle it is a vehicle

Page 141: Ppl for students unit 1,2 and 3

Abstract Classes and Methods

Abstract method – only declaration and no method body

abstract void f();

A class containing abstract methods is called an abstract class

You cannot instantiate an abstract class

Derived class must provide method definitions for all abstract methods, otherwise it itself will have to be abstract

An abstract class may not have any abstract method when you simply want to prevent instantiation

Page 142: Ppl for students unit 1,2 and 3

Final classes and methods

“This cannot be changed”

final data

final methods

final classes

Page 143: Ppl for students unit 1,2 and 3

final data

To indicate that this piece of data is constant compile time constant

allows calculations to be done at compile time, avoiding any run-time overhead

final float PI=3.14;

final vs static – don’t get confused!

run-time constant

Random rand = new Random();

private final int i = rand.nextInt(20);

final primitive – value is constant

final object – reference is constant

final arguments to methods

Page 144: Ppl for students unit 1,2 and 3

final methods

To prevent overriding – like a lock

Also used for efficiency compiler may turn final methods into inline calls

replacing the method call with a copy of actual code in the method body

for large methods, this doesn’t give much improvement – compiler is wise to decide when to do and when not to

private methods in a class are implicitly final

“overriding” a private method – compiler doesn’t give an error! Caution: you have just created a new method!

Page 145: Ppl for students unit 1,2 and 3

final classes

Lock the class to prevent any sub-classing

All methods in a final class are implicitly final

Page 146: Ppl for students unit 1,2 and 3

Interfaces

Abstract provides a part of interface without providing corresponding implementation

Interface provides no implementation at all Provides only form, no implementation Allows multiple inheritance to be implemented in some way

by allowing a class to be upcasted to more than one base type Interface can contain fields, but they are implicitly static and

final Interface methods are implicitly public Used to establish a “protocol” between classes You can upcast to any of these and it works the same way regular class abstract class interface

Page 147: Ppl for students unit 1,2 and 3

Exception Handling

It is ideal to catch errors at compile time

How does one piece of code tell the other piece of code that an error has occurred and something different needs to be done?

Java enforces a formal structure around errors, called exceptions

Exception handling – some error has happened, now either I know how to handle it or I pass it above for somebody else to handle it

Separates “regular” logic with “exception” logic

Page 148: Ppl for students unit 1,2 and 3

Exception Handling

By throwing an exception, you relegate the problem to a higher context

Division – worth checking for “zero”

if you know how to deal with “zero” denominator, fine

else you “throw” an exception

if (den == 0)

throw new Exception(“Denominator is zero!”);

Execution continues by looking for the exception handler

Page 149: Ppl for students unit 1,2 and 3

Exception Handling

Two constructors in all standard exceptions default

String argument

“throw” causes the method to return – but to a different special place and with a special object as return value

Typically you will throw a different class of exception for each different type of error NullPointerException

FileNotFoundException

Standard vs User Defined Exceptions

Page 150: Ppl for students unit 1,2 and 3

Catching an Exception

Define “try block”s in your code

try { //code that might generate exceptions – “throws” keyword

}

You can put all code at one place (inside try block) and deal with all exceptions in one place

Otherwise error checking for every method call and interspersed with normal application logic

Thrown exception must be caught somewhere – exception handlers

Page 151: Ppl for students unit 1,2 and 3

Exception Handlers

try { //code that might throw exceptions

} catch (Type1 id1) { //code to handle exception of type1

} catch (Type2 id2) { //code to handle exceptions of type2

}…

Handlers must appear directly after the try block

Exception handling mechanism goes hunting for the first handler with an argument that matches the type of the exception

Page 152: Ppl for students unit 1,2 and 3

Checked and Unchecked Exceptions

There isn’t anything special between one exception and the next except for the name

Name of the Exception represents the problem that has occurred

Checked – compile time checking is there throws clause must be there

handler must be there

Unchecked exceptions are those which are not forced by compiler to be thrown or handled explicitly These represent bugs in code!!

RuntimeException

StringIndexOutOfBoundsException

Page 153: Ppl for students unit 1,2 and 3

Applet

Java programs can be

Standalone apps (command line or GUI)

Web browser applets (run inside web browser)

Applications have main() method, applets don’t

Applets can’t make changes to machine on which they are running

Eg. writing to disk

Hence only small interactive programs

To make web pages more dynamic and interactive

Page 154: Ppl for students unit 1,2 and 3

Hello World Applet

//Filename: HelloWorldApplet.java

import java.applet.Applet;

import java.awt.Graphics;

public class HelloWorldApplet extends Applet { public void paint(Graphics g) {

g.drawString("Hello World!", 50, 25);

}

}

setColor()

drawRect()

Page 155: Ppl for students unit 1,2 and 3

HTML Code

//Filename: HelloWorldApplet.html

<title>Hello World Applet</title>

</head>

<body>

<applet code="HelloWorldApplet.class" align="baseline“ width="200" height="80"</applet>

</body>

</html>

Page 156: Ppl for students unit 1,2 and 3

Running an Applet

Browser

AppletViewer

Java WebStart

Page 157: Ppl for students unit 1,2 and 3

Applet Methods

init() Called when applet is first created and loaded by underlying software

start() Called when applet is first visited

paint() Called to draw the applet’s panel

stop() When applet is no longer being used, like moving to a different page

destroy() Called when browser exits

Page 158: Ppl for students unit 1,2 and 3

Graphical Programming

AWT – Abstract Windowing Toolkit Cross platform library Powerful API, allows fast GUI development Most of its classes and interfaces can be used for both

applets and applications GUI Components Label Button Panel TextField TextArea … All components extend from Component class

Page 159: Ppl for students unit 1,2 and 3

Component

Window super class for application windows and dialog windows

Frame

Dialog

Panel generic container that can be displayed in an applet or a

window

Applet is a Panel

ScrollPane Scrollable container that can have vertical and horizontal scroll

bars

Page 160: Ppl for students unit 1,2 and 3

Label

java.awt.Label

To display text at a particular location in GUI container

Label();

Label(“Hello”);

Label(“Hello”, CENTER|LEFT|RIGHT);

setText()

getText()

Page 161: Ppl for students unit 1,2 and 3

Button

java.awt.Button

Button();

Button(“Submit”);

setLabel(), getLabel()

addActionListener()

removeActionListener()

Page 162: Ppl for students unit 1,2 and 3

Layout Manager

setLayout() method in the container class Takes an object which implements LayoutManager interface BorderLayout north, south, east, west, center default for Window, Frame and Dialog

CardLayout like a deck of cards

FlowLayout default for Panel

GridLayout Rows and columns

GridBagLayout some components can occupy more than one row or column

Null Layout for absolute positioning setBounds(x,y,l,b)

Page 163: Ppl for students unit 1,2 and 3

Event Handling

Button click, key press, etc. are events

We need to do something when such events are generated – this is called as event handling

Source object

Listener object

adapter class that implements an event listener interface

java.util.EventObject java.awt.AWTEvent java.awt.event.*

EventListener

Page 164: Ppl for students unit 1,2 and 3

Event and Listeners

ActionEvent ActionListener

AdjustmentEvent AdjustmentListener

ComponentEvent ComponentListener

InputMethodEvent InputMethodListener

ItemEvent ItemListener

TextEvent TextListener

Adapter classes in java.awt.event to make life easier

Page 165: Ppl for students unit 1,2 and 3

Choice

To implement pull down lists

Also called option menu or pop-up menu

Allows a user to select one value out of many

Choice()

add(), remove() etc.

ChoiceHandler

Page 166: Ppl for students unit 1,2 and 3

List

More sophisticated than Choice

Lets you specify the size of scrollable window in which list items should be displayed

Allows multiple selection

List(rows, multiple)

add()

ListHandler

Page 167: Ppl for students unit 1,2 and 3

Stand Alone GUIs

Demo!

Page 168: Ppl for students unit 1,2 and 3

Self Study

User Defined Exception

Multi level inheritance

Hierarchical inheritance