CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San...

32
CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak www.cs.sjsu.edu /~mak

Transcript of CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San...

Page 1: CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.

CS 152: Programming Language Paradigms

April 21 Class Meeting

Department of Computer ScienceSan Jose State University

Spring 2014Instructor: Ron Mak

www.cs.sjsu.edu/~mak

Page 2: CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.

SJSU Dept. of Computer ScienceSpring 2014: April 21

CS 152: Programming Language Paradigms© R. Mak

2

Name Resolution and Overloading

Many languages allow you to redefine a name within the same scope.

Example: Redefine the function max, each time with different parameter types or number of parameters._

Page 3: CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.

SJSU Dept. of Computer ScienceSpring 2014: April 21

CS 152: Programming Language Paradigms© R. Mak

3

Java Name Resolution and Overloadingpublic class OverloadMax { private int max(int x, int y) { System.out.print( "int max(int x, int y): "); return x > y ? x : y; } private double max(double x, double y) { System.out.print( "double max(double x, double y): "); return x > y ? x : y; } private int max(int x, int y, int z) { System.out.print( "int max(int x, int y, int z): "); return x > y ? (x > z ? x : z) : (y > z ? y : z); } }

int max(int x, int y) 3double max(double x, double y) : 3.0int max(int x, int y, int z) 4double max(double x, double y) 3.0

public static void main(String[] args) { OverloadMax om = new OverloadMax();

System.out.println(om.max(2, 3)); System.out.println(om.max(2.0, 3.0)); System.out.println(om.max(2, 3, 4)); System.out.println(om.max(2, 3.0));}

(int) 2 (double) 2.0

Page 4: CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.

SJSU Dept. of Computer ScienceSpring 2014: April 21

CS 152: Programming Language Paradigms© R. Mak

4

C++ Operator Overloading

You can overload certain C++ operators such as +. At least one argument must be a user-defined type.

char *concatenate(char *str1, char *str2){ char *cat = (char *) malloc(strlen(str1) + strlen(str2)); strcpy(cat, str1); strcat(cat, str2); return cat;}

int main(){ char *strA = concatenate("Hello", " "); char *strB = concatenate(strA, "world!"); cout << strB << endl;}

Hello world!

Page 5: CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.

SJSU Dept. of Computer ScienceSpring 2014: April 21

CS 152: Programming Language Paradigms© R. Mak

5

C++ Operator Overloading, cont’d

class MyString{ public: char *data;

MyString(char *str) { data = (char *) malloc(strlen(str)); strcpy(data, str); }};

char* operator + (MyString str1, MyString str2){ char *cat = (char *) malloc(strlen(str1.data) + strlen(str2.data)); strcpy(cat, str1.data); strcat(cat, str2.data); return cat;}

Happy Easter!

Rumor: A future version of Javawill support operator overloading.

int main(){ MyString strX("Happy"); MyString strY(" "); MyString strZ("Easter!"); cout << strX + strY + strZ << endl;}

Demo

Page 6: CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.

SJSU Dept. of Computer ScienceSpring 2014: April 21

CS 152: Programming Language Paradigms© R. Mak

6

Data Types

In a programming language, a data type defines:

A set of values Example: integer values, real values, string values

A set of legal operations that can be performed on the values. Example: integer + - * / Example: string length, substring, concatenation,

truncation_

Page 7: CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.

SJSU Dept. of Computer ScienceSpring 2014: April 21

CS 152: Programming Language Paradigms© R. Mak

7

Data Types, cont’d

What can have types?

data values literals variables procedure and function parameters function return values

_

Page 8: CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.

SJSU Dept. of Computer ScienceSpring 2014: April 21

CS 152: Programming Language Paradigms© R. Mak

8

Strongly Typed Language

In a strongly typed language, each variable has a type.

The parser in the front end can perform static type checking._

Page 9: CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.

SJSU Dept. of Computer ScienceSpring 2014: April 21

CS 152: Programming Language Paradigms© R. Mak

9

Advantages of Static Type Checking

Catch more errors during translation. Improve program security and reliability. Improve program readability. Remove ambiguities. Verify interface consistency and correctness. Greater programmer discipline. Generate more efficient object code.

_

Page 10: CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.

SJSU Dept. of Computer ScienceSpring 2014: April 21

CS 152: Programming Language Paradigms© R. Mak

10

Weakly Typed Language

Some attributes of a weakly typed language:

A variable does not have a type and thereforeit can be bound to a value of any type at run time.

Values have types.

Type checking occurs at run time to ensure that operations have arguments of the proper types.

Implicit type conversions can occur at run time._

Page 11: CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.

SJSU Dept. of Computer ScienceSpring 2014: April 21

CS 152: Programming Language Paradigms© R. Mak

11

Advantages of Weakly Typed Languages

Programmers write less code.

Less burden on programmers._

Page 12: CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.

SJSU Dept. of Computer ScienceSpring 2014: April 21

CS 152: Programming Language Paradigms© R. Mak

12

Simple Types

Scalar types Predefined types such as integer, real, character,

boolean, etc.

Enumerated types The programmer explicitly lists

an enumerated type’s values. Each value is named by an identifier. The values are ordered. Operations include predecessor and successor. Example (C): enum Color {RED, GREEN, BLUE};

Page 13: CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.

SJSU Dept. of Computer ScienceSpring 2014: April 21

CS 152: Programming Language Paradigms© R. Mak

13

Simple Types

Subrange types

Values are a contiguous subset of the values of a base type, such as integer or enumeration.

Operations are inherited from the base type.

Examples (Pascal):

TYPE Color = (red, green, blue, yellow, orange, purple); MyColor = blue..orange; SmallInt = 0..9;

Page 14: CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.

SJSU Dept. of Computer ScienceSpring 2014: April 21

CS 152: Programming Language Paradigms© R. Mak

14

Type Constructors

Programmers can create new types by composing other types.

Array types Record or structure types

Operations include field selection.

Classes Fields and methods.

Set types Example (Pascal):

TYPE Color = (red, green, blue, yellow, orange, purple); ColorSet = SET OF Color;

VAR c : Color; warm, cool : ColorSet;

BEGIN c := purple; warm := [red, orange]; cool := [yellow, blue];

IF c IN warm + cool {union} OR c IN warm * cool {intersection} OR [yellow, red] <= warm {contains} THEN ...

END.

Page 15: CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.

SJSU Dept. of Computer ScienceSpring 2014: April 21

CS 152: Programming Language Paradigms© R. Mak

15

Pointer Types

Represents the address of the value of a base type.

Example (C): Variable pchar points to values of the base character type.

Some languages such as C allows explicit pointer arithmetic. Dangerous!

char *pchar;

pchar + 1;

Page 16: CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.

SJSU Dept. of Computer ScienceSpring 2014: April 21

CS 152: Programming Language Paradigms© R. Mak

16

Reference Types

Similar to a pointer type, except that the language does not allow the programmer to manipulate the pointer explicitly.

No pointer arithmetic.

A Java variable of an object type has values that are references to objects of that type._

Page 17: CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.

SJSU Dept. of Computer ScienceSpring 2014: April 21

CS 152: Programming Language Paradigms© R. Mak

17

Type Compatibility

Type A is assignment compatible with type B if:

A value of type A can be assigned to a variable of type B.

Example (Java): Type int is assignment compatible with type float. You can assign an int value to a float variable.

Example (Java): Type int is not assignment compatible with type String. You cannot assign an int value to a String variable.

A value of type A can be passed by value to a parameter of type B.

Page 18: CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.

SJSU Dept. of Computer ScienceSpring 2014: April 21

CS 152: Programming Language Paradigms© R. Mak

18

Type Compatibility, cont’d

Type A is comparison compatible with type B if a type A value can be compared to a type B value.

Example: With some languages, strings of different lengths are comparison compatible. The shorter string is padded at the end with blanks at run time before the comparison is made._

Page 19: CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.

SJSU Dept. of Computer ScienceSpring 2014: April 21

CS 152: Programming Language Paradigms© R. Mak

19

Polymorphism

An interface and some classes that implement it.public interface Food { public void prepare(); public void cook(); public void serve();}

public class Chicken implements Food { public void prepare() { /* preparing */ } public void cook() { /* cooking */ } public void serve() { /* serving */ }}

public class PorkChops implements Food { public void prepare() { /* preparing */ } public void cook() { /* cooking */ } public void serve() { /* serving */ }}

public class Broccoli implements Food { public void prepare() { /* preparing */ } public void cook() { /* cooking */ } public void serve() { /* serving */ }}

Each class that implementsinterface Food must implement

each of the interface’sdeclared methods.

The interface serves as acontract for all users of

the implementing classes.

Page 20: CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.

SJSU Dept. of Computer ScienceSpring 2014: April 21

CS 152: Programming Language Paradigms© R. Mak

20

Polymorphism

Variable food has type Food (an interface). A variable can have an interface type.

Its value is a reference to an object of type Broccoli. A value can have an object type but never an interface type.

public interface Food { public void prepare(); public void cook(); public void serve();}

public class Broccoli implements Food { public void prepare() { /* preparing */ } public void cook() { /* cooking */ } public void serve() { /* serving */ }}

Food food = new Broccoli();food.prepare();food.cook();food.serve();

Type Food Type Broccoli

Page 21: CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.

SJSU Dept. of Computer ScienceSpring 2014: April 21

CS 152: Programming Language Paradigms© R. Mak

21

Polymorphism, cont’d

Because variable food is of the interface type, its value can be a reference to a Broccoli, Chicken, or PorkChop object.

Due to polymorphism, the correct prepare(), cook(), or serve() method is called at run time depending on the type of the value, not the type of the variable.

public interface Food { public void prepare(); public void cook(); public void serve();}

public class Chicken implements Food { public void prepare() { /* preparing */ } public void cook() { /* cooking */ } public void serve() { /* serving */ }}

Food food = new Broccoli();food.prepare();food.cook();food.serve();

Type Food Type Broccoli

Page 22: CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.

SJSU Dept. of Computer ScienceSpring 2014: April 21

CS 152: Programming Language Paradigms© R. Mak

22

Array1: Sort an Array of Integers

Main:

Print:

public static void main(String[] args) { int numbers[] = new int[] {5, 1, 9, 4, 5, 0, 7, 6};

System.out.print("Before sorting:"); print(numbers); sort(numbers); System.out.print(" After sorting:"); print(numbers);}

private static void print(int elements[]){ for (int elmt : elements) { System.out.print(" " + elmt); } System.out.println();}

Primitive int data.

Page 23: CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.

SJSU Dept. of Computer ScienceSpring 2014: April 21

CS 152: Programming Language Paradigms© R. Mak

23

Array1: Sort an Array of Integers, cont’d

Simple exchange sort algorithm:

private static void sort(int elements[]){ for (int i = 0; i < elements.length-1; i++) { for (int j = i+1; j < elements.length; j++) { if (elements[j] < elements[i]) { int temp = elements[i]; elements[i] = elements[j]; elements[j] = temp; } } }}

Page 24: CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.

SJSU Dept. of Computer ScienceSpring 2014: April 21

CS 152: Programming Language Paradigms© R. Mak

24

Array2: Use an ArrayList

Main:

An ArrayList can only store objects of a reference type such as Integer, not primitive type data such as int.

public static void main(String[] args) { ArrayList numbers = new ArrayList(); numbers.add(new Integer(5)); numbers.add(new Integer(1)); numbers.add(new Integer(9)); numbers.add(new Integer(4)); numbers.add(new Integer(5)); numbers.add(new Integer(0)); numbers.add(new Integer(7)); numbers.add(new Integer(6));

System.out.print("Before sorting:"); print(numbers); sort(numbers); System.out.print(" After sorting:"); print(numbers);}

Integer objects.

Page 25: CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.

SJSU Dept. of Computer ScienceSpring 2014: April 21

CS 152: Programming Language Paradigms© R. Mak

25

Array2: Use an ArrayList, cont’d

Print:

A “raw” ArrayList stores Object data. Object is the base of all Java reference types. Therefore, we must coerce each Object element to Integer

with a type cast: Class Integer has an intValue() method:

private static void print(ArrayList elements){ for (Object elmt : elements) { System.out.print(" " + ((Integer) elmt).intValue()); } System.out.println();}

(Integer) elmt

((Integer) elmt).intValue()

Page 26: CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.

SJSU Dept. of Computer ScienceSpring 2014: April 21

CS 152: Programming Language Paradigms© R. Mak

26

Array2: Use an ArrayList, cont’d

Sort:

private static void sort(ArrayList elements){ for (int i = 0; i < elements.size()-1; i++) { for (int j = i+1; j < elements.size(); j++) { if (((Integer) elements.get(j)).intValue() < ((Integer) elements.get(i)).intValue()) { Object temp = elements.get(i); elements.set(i, elements.get(j)); elements.set(j, temp); } } }}

Type coercion needed!

Page 27: CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.

SJSU Dept. of Computer ScienceSpring 2014: April 21

CS 152: Programming Language Paradigms© R. Mak

27

Dangers of Using Raw ArrayList

Since a raw ArrayList holds Object data, and Object is the root of all Java reference types, nothing prevents us from doing this:

What happens at run time?

ArrayList numbers = new ArrayList();numbers.add(new Integer(5));numbers.add(new Integer(1));numbers.add(new Integer(9));numbers.add(new Integer(4));numbers.add(new Date());numbers.add(new Integer(0));numbers.add(new Integer(7));numbers.add(new Integer(6));

Page 28: CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.

SJSU Dept. of Computer ScienceSpring 2014: April 21

CS 152: Programming Language Paradigms© R. Mak

28

Array3: Use ArrayList<Integer>

public static void main(String[] args) { ArrayList<Integer> numbers = new ArrayList<>(); numbers.add(new Integer(5)); numbers.add(new Integer(1)); numbers.add(new Integer(9)); numbers.add(new Integer(4)); numbers.add(new Integer(5)); numbers.add(new Integer(0)); numbers.add(new Integer(7)); numbers.add(new Integer(6));

System.out.print("Before sorting:"); print(numbers); sort(numbers); System.out.print(" After sorting:"); print(numbers);}

Now the compiler will prevent us from adding anything other than Integer data to the array list.

Page 29: CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.

SJSU Dept. of Computer ScienceSpring 2014: April 21

CS 152: Programming Language Paradigms© R. Mak

29

Array3: Use ArrayList<Integer>, cont’dprivate static void print(ArrayList<Integer> elements){ for (Integer elmt : elements) { System.out.print(" " + elmt.intValue()); } System.out.println();}

private static void sort(ArrayList<Integer> elements){ for (int i = 0; i < elements.size()-1; i++) { for (int j = i+1; j < elements.size(); j++) { if (elements.get(j).intValue() < elements.get(i).intValue()) { Integer temp = elements.get(i); elements.set(i, elements.get(j)); elements.set(j, temp); } } }}

We no longer need to coerceelement data to Integer because that’s the only allowable data type in ArrayList<Integer>.

Page 30: CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.

SJSU Dept. of Computer ScienceSpring 2014: April 21

CS 152: Programming Language Paradigms© R. Mak

30

Boxing and Unboxing

Boxing We “wrap” the primitive int value 3

inside an Integer object:

Unboxing We “unwrap” a primitive int value

from an Integer object:

Java does autoboxing/unboxing as necessary, so we don’t have to explicitly do it in our code.

int i = obj.intValue()

Integer obj = new Integer(3);

Page 31: CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.

SJSU Dept. of Computer ScienceSpring 2014: April 21

CS 152: Programming Language Paradigms© R. Mak

31

Array4: Autobox/Unbox

public static void main(String[] args) { ArrayList<Integer> numbers = new ArrayList<>(); numbers.add(5); numbers.add(1); numbers.add(9); numbers.add(4); numbers.add(5); numbers.add(0); numbers.add(7); numbers.add(6);

System.out.print("Before sorting:"); print(numbers); sort(numbers); System.out.print(" After sorting:"); print(numbers);}

Java will autobox each int valueto an Integer object beforeadding it to the array list.

Page 32: CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.

SJSU Dept. of Computer ScienceSpring 2014: April 21

CS 152: Programming Language Paradigms© R. Mak

32

Array4: Autobox/Unbox, cont’dprivate static void print(ArrayList<Integer> elements){ for (Integer elmt : elements) { System.out.print(" " + elmt); } System.out.println();}

private static void sort(ArrayList<Integer> elements){ for (int i = 0; i < elements.size()-1; i++) { for (int j = i+1; j < elements.size(); j++) { if (elements.get(j) < elements.get(i)) { Integer temp = elements.get(i); elements.set(i, elements.get(j)); elements.set(j, temp); } } }}

Auto-unbox the int valuefrom an Integer object.

Auto-unbox the int valuefrom an Integer object.