2. 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
3. Text Books
“Programming Languages Design and
Implementation”
Pratt and Zelkowitz
“Java: The Complete Reference”
Herbert Schildt
4. 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
5. 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)
7. 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
8. Role of Programming Languages
Notations used for specifying, organizing and
reasoning about computations
Providing ways of organizing computations to
achieve the desired effect
9. 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
10. 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
11. 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
12. 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
13. 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
14. Characteristics of a good programming language
Efficiency (cost of use)
program execution
program translation
program creation, testing and use
maintenance
Regularity
Generality
Orthogonality
Uniformity
15. Efficiency – cost of use
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
Chapter 3 Louden
16. Other kinds of efficiency
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
Chapter 3 Louden
17. Features that aid efficiency of execution
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
Chapter 3 Louden
18. Note conflicts with efficiency
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]
Chapter 3 Louden
19. Regularity – Consistency in Design
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?
Chapter 3 Louden
20. Generality deficiencies
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)
Chapter 3 Louden
21. Orthogonality: independence
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
Chapter 3 Louden
22. Examples of limitations
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
Chapter 3 Louden
23. Orthogonality
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.
Chapter 3 Louden
24. Examples of non-orthogonality – C++
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.
Chapter 3 Louden
25. Non-regularity examples from C++
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
Chapter 3 Louden
26. What about Java?
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.)
Chapter 3 Louden
27. Java regularity, continued
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.
Chapter 3 Louden
28. Other design principles
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”
Chapter 3 Louden
29. Other design principles
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
Chapter 3 Louden
30. Other design principles
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
Chapter 3 Louden
31. Other design principles
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?
Chapter 3 Louden
32. Other design principles
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?
Chapter 3 Louden
33. 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?
34. Wikipedia moment:
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.
Chapter 3 Louden
35. 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
36. 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
37. 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
38. 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
39. 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
40. 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
41. 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
42. 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
43. 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
44. 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
46. 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
47. Imperative
Sequence of actions
Heavily based on von Neumann architecture
Variables, assignments and iterative repetitions
FORTRAN, ALGOL, PASCAL, C
48. Procedural
When imperative programming is combined with
subprograms, it is called procedural programming
Obvious Problems
Solved using concept of Modules
50. 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
51. 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
53. Procedural vs Object-Oriented
Emphasis on procedural Emphasis on data
abstraction. abstraction.
Top-down design; Step- Bottom-up design;
wise refinement. Reusable libraries.
Suited for programming Suited for programming
in the small. in the large.
Easy to add new Easy to add new data
operations – only representations – only
additive changes additive changes
54. 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))…)
55. 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)
56. Quick Look
A programming language is a problem-solving tool.
program = algorithms + data
Imperative style: good for decomposition
program = functions o functions
Functional style: good for reasoning
program = objects + messages
Object-oriented style: good for modeling(!)
Other styles and paradigms: blackboard, pipes and filters,
constraints, lists, ...
58. Procedural vs Functional
58
Program: a sequence of Program: a collection of
instructions for a von function definitions (m/c
Neumann m/c. independent).
Computation by Computation by term
instruction execution. rewriting.
Iteration. Recursion.
Modifiable or updateable Assign-only-once
variables. variables.
L5Pdm cs784(Prasad)
59. 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
60. Declarative Languages
Problem specification using functions or relations
Functional (apply functions to given parameters)
Logic (deductive reasoning, rule based)
61. 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
63. 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
67. 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!
68. 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”);
69. ELSE-IF
Multi-way decision
If (expression)
Statement
Else if (expression)
Statement
...
Else
Statement
Last else is optional
Improves efficiency – by skipping evaluation
71. 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
72. Test your skills
While (x != 3) {
i=i-1;
}
Can you write this using for?
74. 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
75. 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
77. 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
78. 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, &, .
79. 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
80. 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
81. Pointer operations
Indirection or dereferencing operator: *
int x=1;
Int *px;
Px = &x;
Y= *px + 1
(*px)++ vs *px++
Px = py
82. 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
83. 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;
}
84. 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!
85. 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
86. Benefits of Procedures
Procedure Abstraction
Focus on “what” instead of “how”
Implementation Hiding
Modular Programs
Libraries
87. Elements of a procedure
Name
Body
Formals
Placeholders for actuals
Result type (optional)
89. 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
90. Local and Global Variables
Local recognized only within a single function
Global recognized in two or more functions
91. 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
92. 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
93. 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
94. 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”
95. 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
96. 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
97. 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?
98. 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
99. 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
100. 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
101. 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
102. 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
103. 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
104. 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
107. 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
108. 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
109. 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
110. 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
112. 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
113. 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. What is an object?
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.
Tangible Things as a car, printer, ...
Roles as employee, boss, ...
Incidents as flight, overflow, ...
Interactions as contract, sale, ...
Basic run-time unit
114
114
115. An Object has …
State Internal data called Fields
Guaranteed to be initialized
Behavior Methods
Identity Unique address somewhere identity
116. Classes Customer
Name
Address
User defined Data type, Just as your Age
structures in C. Account No.
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
117. 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
118. 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
119. 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
120. 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”
121. 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
122. 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
123. 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
124. 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
125. 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
126. 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
127. 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()
128. 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
129. 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!
130. 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
132. 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
133. 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”
134. 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
135. 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
136. Overriding and hiding fields and methods
Upcasting and downcasting
Polymorphism
137. 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”
138. 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
139. 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.
140. 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
141. 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
142. Final classes and methods
“This cannot be changed”
final data
final methods
final classes
143. 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
144. 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!
145. final classes
Lock the class to prevent any sub-classing
All methods in a final class are implicitly final
146. 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
147. 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
148. 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
149. 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
150. 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
151. 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
152. 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
153. 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
154. 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()
157. 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
158. 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
159. 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
160. Label
java.awt.Label
To display text at a particular location in GUI
container
Label();
Label(“Hello”);
Label(“Hello”, CENTER|LEFT|RIGHT);
setText()
getText()
162. 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)
163. 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
164. 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
165. 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
166. 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