0% found this document useful (0 votes)
144 views15 pages

SE323 Final&As

The document discusses exception handling and continuation design in languages. It explains that exception handling deals with special processing for exceptions while continuation refers to where program execution continues after an exception is handled. It also describes how C++/Java handles continuation by resuming execution at the statement after the try block. The document is answering questions on these topics.

Uploaded by

liside7602
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
144 views15 pages

SE323 Final&As

The document discusses exception handling and continuation design in languages. It explains that exception handling deals with special processing for exceptions while continuation refers to where program execution continues after an exception is handled. It also describes how C++/Java handles continuation by resuming execution at the statement after the try block. The document is answering questions on these topics.

Uploaded by

liside7602
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

CHAPTER 14 Exception Handling and Event Handling

QUESTION:
Define the terms exception handling and continuation. List three continuation possibilities in
language exception design. How does C++/Java address continuation design issue?
ANSWER
The special processing that may be required when an exception is detected is called exception handling.

After an exception handler executes, either control can transfer to somewhere in the program outside of
the handler code or program execution can simply terminate. We simply call this continuation.

1. Termination
2. Resume reexecuting the statement that raised the exception,
3. Resume with the statement after the statement that raised the exception

C++/Java Continuation:

After a handler has completed its execution, control flows to the first statement following the try construct
(the statement immediately after the last handler in the sequence of handlers of which it is an element).

CHAPTER 12 Support for OOOP


QUESTION 1 ( 12 Points) 2011-2012 Final (C++ Version)
Identify each of the following Java examples as exhibiting parametric polymorphism, inheritance
polymorphism or ad-hoc polymorphism.
a) (2 pts)
class A { ANSWER:
public int x;
public int getx() {return x;}
public A() {x = 3;}
}

class B extends A {
public int x;
B() { x = 5; }
public int getx() { return x; }
}

A a = new B();

b) (2 pts) class C { ANSWER:


private int x;
public int getx() {return x;}
public void M() {x = 7;}
public void M(int y) {x = y;}
}

(2 pts)
class P <E> { ANSWER:
private E x;
public E getx() {return x;}
public P(E arg) {x = arg;}
}

c) (3 pts) What is the value of a.getx() in example a) above? Explain.


Answer:
d) (3 pts) What is the value of a.x in example a) above? Explain.
Answer:
ANSWER:
a) Inheritance
b) ad-hoc
c) Parametric
d) 5 getx() is polymorphic. getx() from B is used not from A.
e) 3. x is not polymorphic

CHAPTER 11 ADT
QUESTION:
Implement a ADT called SafeBox to store only ONE valuable: Gold. Write two constructors to create an
empty SafeBox or with one valuable in it. One can add or remove valuable to the SafeBox. Write a
main to create a Gold class and store SafeBox. Do not do any error checking.
ANSWER:

public class SafeBox {


private Gold element;
public SafeBox (Gold arg) { element = arg;}
public SafeBox () {element = null;}
Gold remove () {
Gold val = element; element = null; return val;
}
void add (Gold arg) { element = arg;}
public static void main(String[] args) {
Gold g = new Gold(18);

SafeBox safe = new SafeBox (g);


Gold g1 = safe.remove();
System.out.println(g1.getGrade());
}
}

class Gold {
private int grade; // 18, 22, 24
public Gold (int c) { grade = c;}
int getGrade() {return grade;}
}

QUESTION:
Add Exception Handling to the remove method. If there is no item in the SafeBox and you want to
remove something raise an exception and handle it.
ANSWER:
package safeBoxNoGeneric;
import java.lang.NullPointerException;
public class SafeBox {
private Gold element;
public SafeBox (Gold arg) { element = arg;}
public SafeBox () {element = null;}
Gold remove () {
if (element == null) {
throw new NullPointerException();
}
Gold val = element; element = null; return val;
}
void add (Gold arg) { element = arg;}
public static void main(String[] args) {
Gold g = new Gold(18);

SafeBox safe = new SafeBox (g);


Gold g1 = safe.remove();
System.out.println(g1.getGrade());
try {
g1 = safe.remove();
} catch (NullPointerException e) {
System.out.println("No Gold in SafeBox");
}
}
}
CHAPTER 10 Implementing Subprograms
QUESTION: Show the stack with all activation record instances, including the dynamic chain, when
execution reaches position 1 in the following skeletal program. This program uses the deep-access method
to implement dynamic scoping.
QUESTION: Assume that the program is implemented using the shallow-access method using a stack for
each variable name. Show the stacks for the time of the execution of fun2, assuming execution found its
way to that point through the sequence of calls shown in Problem.

void fun1() { The calling sequence for this program for execution to
float a; reach fun2 is
. . .
main calls fun3
}
void fun2() { fun3 calls fun3
int b, d; fun3 calls fun1
. . . <-------- 1 fun1 calls fun2
}
void fun3() {
float d;

}
void main() {
char a, *f, g;
. . .
}
ANSWER:

QUESTION: Show the stack with all activation record instances, including static and dynamic chains, when
execution reaches position 1 in the following skeletal program. Assume Bigsub is at level 1.
QUESTION: Give the (chain_offset, local_offset) pairs for all the variables visible at position 1.

procedure Bigsub is
MySum : Float;
procedure A is
X : Integer;
procedure B(Sum : Float) is
Y, Z : Float;
begin -- of B
. . .
C(Z)
. . .
end; -- of B
begin -- of A
. . .
B(X);
. . .
end; -- of A
procedure C(Plums : Float) is
begin -- of C
. . . <------------------ 1
end; -- of C
L : Float;
begin -- of Bigsub
. . .
A;
. . .
end; -- of Bigsub
ANSWER:
CHAPTER 9 Subprograms
QUESTION: Consider the following program written in some language using C-like syntax:
void exchange(int n1, int n2) {
int store;
store = n2;
n2 = n1;
n1 = store;
}
void main() {
int value = 4, list[5] = {7, 6, 3, 1, 2};
exchange(value, list[0]);
exchange(list[2], list[3]);
exchange(list[value], value);
}

For each of the following parameter-passing methods, what are all of the values of the variables value
and list after each of the three calls to exchange? Use the initial values of list and value before
every call to exchange.
a) Pass-by-value
b) Pass-by-reference
c) Pass-by-value-result
ANSWER:

a. 4 and 7,6,3,1,2 b. 7 and 4,6,3,1,2 c. 7 and 4,6,3,1,2


4 and 7,6,3,1,2 4 and 7,6,1,3,2 4 and 7,6,1,3,2
4 and 7,6,3,1,2 2 and 7,6,3,1,4 2 and 4,6,3,1,4
CHAPTER 8 Statement-Level Control Structures
Selection (if,switch), Iteration (for, while, do-while), branch (goto)
Principal paradigms for control flow:
 sequencing
 selection
 iteration

Selection if ... then ... else


if ... then ... elsif ... else
case/switch
Iteration pre-test while (...) {...}
post-test do { ... } while(...)
counter-controlled for (i = first; i <= last; i+= step) {
...
}
Equivalent to
i = first;
while (i <= last) {
...
i += step;
}
Recursion

iterator objects ( C++, Java)

Standard interface for abstraction to drive for loops. In Java :


List myList = ...;
for (Object o : myList) {
// use object o
}
(There are generic versions of this that avoid the need to cast from Object to a desired class.)
requires that the to-be-iterated class (here, List) implements the Iterable interface, which exports a
method
public Iterator iterator()
where Iterator is an interface exporting methods
public boolean hasNext() and public Object next()

The for loop is syntactic sugar for


for (Iterator i = myList.iterator(); i.hasNext();) {
Object o = i.next();
// use object o
}
CHAPTER 7 Expressions and Assignment Statements
Assignment, Relational and Boolean expressions, arithmetic expressions etc
Expression evaluation
precedence and associativity
C has 15 levels -- too many to remember
Lesson: when unsure, use parentheses!
associativity may be dangerous.
(a + b) + c works if a is MININT (negative) and b is MAXINT and c is positive small
a + (b + c) may not work (overflow)
short-circuiting
if (b != 0 && a/b == c) ...
Side Effects
 Often discussed in the context of functions.
 a side effect is some permanent state change caused by execution of function -- some
noticeable effect of call other than return value.
CHAPTER 6 Data Types
Primitive types (char, int, double, bool etc), enum, array, record, union, pointers, strong vs weak type
checking,)
STRONG TYPING means, informally, that the language prevents you from applying an operation to
data on which it is not appropriate.
STATIC TYPING means that the compiler can do all the checking at compile time.

When an expression of one type is used in a context where a different type is expected, one normally
gets a type error. BUT Many languages allow things like this.

int a; double b, c;
...
c = a + b;
type conversions (explicit)
type coercions (implicit)

casts (breaking the typing rules) c = (double) a

Discrete types -- integer, boolean, char, enumeration


countable
Scalar types R-real, complex
Composite types records/structs (unions),arrays, strings, pointers
Records usually laid out contiguously
Unions overlay space, cause problems for type checking
Arrays contiguous elements, column major, row major
Pointers Note that pointers are NOT the same thing as addresses. Pointers are an
abstraction. Addresses are an implementation. Pointers are NOT always
implemented as addresses. However, In C and C++ pointers are addresses

pointers serve two purposes:


 efficient (and sometimes intuitive) access to objects (indirect addressing as in C/C++)
 dynamic creation of linked data structures, in conjunction with a heap storage manager
(dynamic memory management
dangling pointers
due to explicit deallocation of heap objects
only in languages that *have* explicit deallocation
In Java you can not have dangling pointers. There is NO explicit deallocation. There is
GARBAGE COLLECTOR in Java.

C pointers and arrays

float stuff[100];
float *p;
p = stuff;

*(p+5) is equivalent to stuff[5] and p[5]


*(p+i) is equivalent to stuff[i] and p[i]
n = stuff[2] but also n = 2[stuff]

Choice between pointer arithmetic & subscripts is largely a matter of taste.


CHAPTER 5 Names, Bindings and Scopes
Static vs. Dynamic binding, Storage bindings (static, stack-dynamic, explicit heap-dynamic, implicit
heap-dynamic, static vs dynamic scope, referencing environment.

 The terms STATIC and DYNAMIC are generally used to refer to things bound before run time and at
run time, respectively.
 With STATIC (LEXICAL) SCOPE RULES, a scope is defined in terms of the physical (lexical) structure of
the program.
 Most programming languages today employ static scope rules.
 With DYNAMIC SCOPE RULES, bindings depend on the current state of program execution. They
cannot always be resolved by examining the program because they are dependent on calling
sequences.
example: static vs dynamic scope rules

int a
procedure first:
a := 1
procedure second:
int a
first()

a := 2; second(); write(a)

If static scope rules are in effect, the program prints a 1. If dynamic scope rules are in effect, the
program prints a 2.

A binding is an association between two entities, such as a name and the thing it names.
Binding Time is the point at which a binding is created or, more generally, the point at which any
implementation decision is made.
Examples include
language design time
program structure, possible types
language implementation time
binding type to a representation. i.e. floating point
compile time
bind a variable to a type
link time
layout of whole program in memory
load time
choice of physical addresses
run time
value/variable bindings, sizes of strings

if object outlives binding it's garbage


if binding outlives object it's a dangling reference

The period of time from creation to destruction is called the LIFETIME of a binding. The textual
region of the program in which the binding is *active* is its SCOPE.
CHAPTER 4 Lexical and Syntax Analysis
Lexical Analysis, Parsing
Lexical Analyzer is responsible for tokenizing the source program.
Lexical Analyzer can be built based on Finite State Automata.
A parser is a language *recognizer*.
Top down Parsing: Recursive descent parser
CHAPTER 3 Describing Syntax and Semantics
BNF, Ambiguity, Precedence, Associativitiy
Terminology:
Context Free Grammar
symbols
terminals (tokens)
non-terminals
start symbol
production
derivation (see example below)
left-most
right-most
sentential form
It's particularly important that it be UNAMBIGUOUS -- no two parse trees for the same string.
<expr> -> <factor> | <expr> - expr> (ambiguous)

<expr> -> <factor> | <expr> - factor> (unambiguous, left associativity)


CHAPTER 1 Preliminaries
Group languages as

Imperative Fortran, Ada, Pascal, Basic, C, ...


(based on von Neumann Architecture)
Object-oriented Smalltalk, Eiffel, C++ ?, Java, C#, ...)
Functional Scheme, ML, pure Lisp, Haskell, F#)
Logic Prolog

Language implementation: interpreters & compilers

phases of compilation:
character stream
scanner (lexical analysis)
token stream
parser (syntax analysis)
drives the whole process
parse tree
semantic analysis
abstract syntax tree (AST)
intermediate code generation
intermediate form of some sort
optimization

target code
machine code

You might also like