Lecture 21 (Edwards) - Types

Lecture Date: Monday, April 6

illustration of type by location or by label Courtesy of Professor Tychonievich.

How do you remember what is Jim’s phone number? Do you leave it on a postit note on your desk and just remember that the number there must be Jim’s? Or do you Write Jim’s name on the postit note and leave it some where in your room?

This first way of keeping information is known as “static” since it is dependent on the position of the informaiton. The second we call “dynamic” since the information could be moved anywhere.

Computers have the same issue: Remember that computers store information in binary (instead of base 10) but this means that everything is really a number. A computer needs to know if that sequence of 0’s and 1’s are for an int or a double or a String, etc.

Java is a statically typed language. When we say ‘int x’ we are saying create a box called ‘x’ and it can only hold ints. I can write ‘x=3;’ but I cannot write ‘x=“hello”’. In a dynamic language this is allowed.

As we talk about type systems and languages, we’ll think about how they impact the following:

  • ease of writing programs
  • program runtime speed
  • liklihood of bugs
  • ease of reading the program a month from now
  • ability to run the program on a particular device

After this we will start talking about what makes good code. Have a look at the following and see which you think is better code.

int x = a; int y = b; // swap x and y: int tmp = x; // x = a, y = b, tmp = a x = y; // x = b, y = b, tmp = a y = tmp; // x = b, y = a, tmp = a

int x = a; int y = b; // swap x and y: x -= y; // x = a-b, y = b y += x; // x = a-b, y = b+(a-b) = a x = y - x; // x = a-(a-b) = b, y = a

Which one is faster to run? Faster to write? Easier to understand? More likely to work?