Pplforstudents Unit12and3 120418120825 Phpapp02
Pplforstudents Unit12and3 120418120825 Phpapp02
Pplforstudents Unit12and3 120418120825 Phpapp02
Languages
CS20105: SE E
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
What is a PL?
Vocabulary and set of grammatical rules for instructing a
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
ML theorem proving
SmallTalk - Dynabook
Clu, SML Modules modular programming
C++ - object orientation
Java internet applications
Categories of Languages
Machine Language
0s and 1s
Unintelligible
code
Unsuitable for programming
Assembly Language
High-Level Langauges
Language Implementation
Compiler
Interpreter
Regularity
Generality
Orthogonality
Uniformity
Chapter 3 Louden
Chapter 3 Louden
access.
Manual memory management avoids overhead of
garbage collection.
Simple semantics allow for simple structure of
running programs
Chapter 3 Louden
Chapter 3 Louden
Generality deficiencies
20
Chapter 3 Louden
Orthogonality: independence
21
Chapter 3 Louden
Examples of limitations
22
Chapter 3 Louden
Orthogonality
23
Chapter 3 Louden
Lack of uniformity
Chapter 3 Louden
Chapter 3 Louden
Chapter 3 Louden
Chapter 3 Louden
damage. (Java)
discourages errors
allows errors to be discovered
type checking
Chapter 3 Louden
Chapter 3 Louden
Is C portable?
C source code is portable if you have not entered into
Wikipedia moment:
34
Chapter 3 Louden
Human Intervention
Most of the Languages cannot handle these
constraints
OOP hardly support any requirements for BATCH
Processing of JOBS.
Scripting languages
Use of CPU
Memory
Underlying OS
Usability
Ease of USE
Language Syntax
Functionality/Capability
structures
Abstraction
Scope and Binding as a technique which simplifies
capabilities
facilities
Programming Paradigms
How will you define Programming Paradigm ?
Its simply the STYLE of Computer Programming
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
Imperative
Sequence of actions
Procedural
When imperative programming is combined with
Example
Object Oriented
Eliminate drawbacks of conventional programming
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
Object Oriented
How What
Withdraw, deposit,
transfer
Customer, money,
account
Procedural vs Object-Oriented
Emphasis on procedural
Emphasis on data
abstraction.
Top-down design; Stepwise refinement.
Suited for programming
in the small.
Easy to add new
operations only
additive changes
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
Example
A functional version (in Haskell) has a different feel to it:
Fibonacci numbers, functional style
-- describe an infinite list based on the recurrence
Quick Look
A programming language is a problem-solving tool.
Imperative style:
Functional style:
Object-oriented style:
Functional vs Imperative
Refer doc at C:\VIT\PPL\TE PPL\UNIT 1\TE PPL
Notes
Procedural vs Functional
58
Program: a sequence of
Program: a collection of
L5Pdm
cs784(Prasad)
Logic
execute by checking for the presence of
Declarative Languages
Problem specification using functions or relations
Concurrent
Parallel execution of processes.
algorithms
Examples: Concurrent C, Java, Fortran-90
Self Study
Comparison of different programming paradigms
Imperative Languages
CRs PASCAL and C
Action statements
Sequential statements
Selection statements
Iteration statements
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
IFELSE
If (expression)
Statement1
Else
Statement2
Else is optional
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
Post-test
FOR
Initializer
Loop condition
Incrementer
All 3 are optional: what about condition?
Nested Loop
Jump Statements
Unconditional branch
GOTO label
BREAK
CONTINUE
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
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
Data Types in C
Type Checking
checking that each operation receives the proper
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
Int ival;
Float fval;
Char *sval;
} u;
U is large enough to hold the largest member
Programmers responsibility to keep track of whats
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
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
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
Register
Stored in register
Static
Static automatic variables continue to exist even
Extern
Scope: global
Life: from point of definition through the remainder of
the program
Defined outside of all functions
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
call occurs
Two main types
Call by value
Call by reference
Other Methods
call by name
call by value-result
call by result
Activation Records
A declaration can be bound to a different location,
procedure at a time
Procedure executes completely before returning
control
LIFO manner
Activation Tree
Recursion
Recursion is a programming technique that allows
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
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
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
Self Study
Structure
to do by sending messages
objects
Every object has a type
messages
What is an object?
An object represents an individual, identifiable item, unit, or
114
114
An Object has
State Internal data called Fields
Guaranteed to be initialized
Behavior Methods
Identity Unique address somewhere identity
Classes
Customer
Name
Address
Age
Account No.
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
Key Points
You manipulate objects with references
String s;
only reference, not the object
You must create all the objects
String s = abcd
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
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
{
}
Saves programmer, but then requires a garbage collector
Eliminates memory leak
Constructors
Every object must be created
EXACTLY
In Java, creation and initialization are unified
concepts
Method Overloading
Using the same name for different purposes instead
Shirt
Car
Dog
argument types
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
static keyword
Normally you need an instance of a class to be able to
do something meaningful
How about?
this keyword
Only one method in a class
Yet a.f(1) and b.f(1) are different. How does the method
Banana.f(a,1);
Banana.f(b,1);
otherwise error
methods
static methods are like global functions
static is not object oriented!
never again
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
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
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
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
Composition vs Inheritance
Composition is more flexible
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
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 runtime overhead
final float PI=3.14;
final vs static dont get confused!
run-time constant
Random rand = new Random();
private final int i = rand.nextInt(20);
final methods
To prevent overriding like a lock
give an error!
final classes
Lock the class to prevent any sub-classing
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
Exception Handling
By throwing an exception, you relegate the problem
to a higher context
Division worth checking for zero
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
NullPointerException
FileNotFoundException
Catching an Exception
Define try blocks in your code
try {
//code that might generate exceptions throws keyword
}
You can put all code at one place (inside try block)
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
Applet
Java programs can be
Standalone apps (command line or GUI)
Web browser applets (run inside web browser)
Applications have main() method, applets dont
Applets cant make changes to machine on which
setColor()
drawRect()
HTML Code
//Filename: HelloWorldApplet.html
<applet code="HelloWorldApplet.class"
align="baseline width="200"
height="80"</applet>
</body>
</html>
Running an Applet
Browser
AppletViewer
Java WebStart
Applet Methods
init()
start()
paint()
stop()
destroy()
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
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
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
java.util.EventObject java.awt.AWTEvent
java.awt.event.*
EventListener
AdjustmentEvent AdjustmentListener
ComponentEvent ComponentListener
InputMethodEvent InputMethodListener
ItemEvent ItemListener
TextEvent TextListener
Choice
To implement pull down lists
List
More sophisticated than Choice
Self Study
User Defined Exception