Upload
akshay-nagpurkar
View
1.832
Download
0
Tags:
Embed Size (px)
Citation preview
C S 2 0 1 0 5 : S E ‘ E ’
Principles of Programming Languages
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
Text Books
“Programming Languages Design and Implementation”
Pratt and Zelkowitz
“Java: The Complete Reference”
Herbert Schildt
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
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)
Application Domains
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
Role of Programming Languages
Notations used for specifying, organizing and reasoning about computations
Providing ways of organizing computations to achieve the desired effect
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
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
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
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
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
Characteristics of a good programming language
Efficiency (cost of use)
program execution
program translation
program creation, testing and use
maintenance
Regularity
Generality
Orthogonality
Uniformity
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
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
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
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]
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?
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)
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
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
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.
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.
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
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.)
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.
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”
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
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
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?
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?
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?
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.
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
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
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
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
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
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
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
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
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
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
Programming Paradigms
Imperative/Procedural/Operational
Declarative
Functional/Applicative
Logic/Rule-based
Object Oriented
Scripting
Concurrent
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
Imperative
Sequence of actions
Heavily based on von Neumann architecture
Variables, assignments and iterative repetitions
FORTRAN, ALGOL, PASCAL, C
Procedural
When imperative programming is combined with subprograms, it is called procedural programming
Obvious Problems
Solved using concept of Modules
Example
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
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
Procedural vs. Object-Oriented
Procedural
Withdraw, deposit, transfer
Object Oriented
Customer, money,
account
How What
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
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))…)
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)
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, ...
Functional vs Imperative
Refer doc at C:\VIT\PPL\TE PPL\UNIT 1\TE PPL Notes
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.
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
Declarative Languages
Problem specification using functions or relations
Functional (apply functions to given parameters)
Logic (deductive reasoning, rule based)
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
Self Study
Comparison of different programming paradigms
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
Constants and Variables
Operators
Arithmetic
Logical
Relational
Associativity
Precedence
Difference between = and ==?
++ and --
Selection Statements
Control Statements / Branch Statements
IF-ELSE
Nested IF-ELSE
Conditional Expression
Switch statements
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!
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”);
ELSE-IF
Multi-way decision
If (expression) Statement
Else if (expression) Statement
...
Else Statement
Last else is optional
Improves efficiency – by skipping evaluation
SWITCH
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
Test your skills
While (x != 3) {
i=i-1;
}
Can you write this using for?
Nested Loop
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
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
Data Types in C
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
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, &, .
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
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
Pointer operations
Indirection or dereferencing operator: *
int x=1;
Int *px;
Px = &x;
Y= *px + 1
(*px)++ vs *px++
Px = py
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
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;
}
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!
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
Benefits of Procedures
Procedure Abstraction
Focus on “what” instead of “how”
Implementation Hiding
Modular Programs
Libraries
Elements of a procedure
Name
Body
Formals
Placeholders for actuals
Result type (optional)
Blocks
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
Local and Global Variables
Local recognized only within a single function
Global recognized in two or more functions
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
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
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
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”
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
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
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?
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
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
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
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
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
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
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
How Does It Work?
How Does It Work?
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
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
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
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
Self Study
Structure
Generic Templates in C++
Library Classes in C++
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
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
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
An Object has …
State Internal data called Fields
Guaranteed to be initialized
Behavior Methods
Identity Unique address somewhere identity
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.
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
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
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
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”
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
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
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
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
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
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
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()
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
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!
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
Reusing classes
Can be done in two ways
composition
inheritance
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
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”
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
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
Overriding and hiding fields and methods
Upcasting and downcasting
Polymorphism
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”
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
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.
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
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
Final classes and methods
“This cannot be changed”
final data
final methods
final classes
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
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!
final classes
Lock the class to prevent any sub-classing
All methods in a final class are implicitly final
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
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
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
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
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
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
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
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
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()
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>
Running an Applet
Browser
AppletViewer
Java WebStart
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
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
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
Label
java.awt.Label
To display text at a particular location in GUI container
Label();
Label(“Hello”);
Label(“Hello”, CENTER|LEFT|RIGHT);
setText()
getText()
Button
java.awt.Button
Button();
Button(“Submit”);
setLabel(), getLabel()
addActionListener()
removeActionListener()
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)
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
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
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
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
Stand Alone GUIs
Demo!
Self Study
User Defined Exception
Multi level inheritance
Hierarchical inheritance