Lecture 33 (Sherriff) - Type Systems

Lecture Date: Monday, April 6

We’ll pick up with looking one more time at our poor, discarded kittens from Friday. Specifically, we’ll look at how we kept up with the kitten’s ID number.

We’ll move on from there to talk about data types. How exactly does Java keep up with what type a variable is? How do other languages do it?

The War between Filing Systems

There are lots of numbers in your life. Social security numbers, student ID numbers, SIS person numbers, telephone numbers, zip codes, … How do you know which number is which?

Option 1: remember. This number is on the post-it beside my bed, which is where I wrote my student ID number, so that must be what it is.

Option 2: annotate. This piece of paper says SSN: 012345678 so it must by my SSN, not my telephone number.

In programming we call the first static typing and the latter dynamic typing. People argue about which one is better heatedly.

Java happens to be statically typed. Other languages, like Python, are dynamically typed.

How does this affect how we write our programs?

Imagine a program that you might write that has these lines:

1
2
3
x = 4;
x = "Hello World";
x = new Kitten();

In Java, this would never work, because we would have defined x to have a particular type. After that, it can’t be changed. But, if we store the type with the data itself and not the variable, then this works just fine. x is just a pointer to some data - how we interpret it is up to the programmer.

You might think that dynamic typing can get a programmer in a lot of trouble if they don’t keep their variables straight. And you’re right. But it does make for less coding in general, even if dynamically typed languages are usually slower than statically typed ones.

Java is also a strongly typed language, which means that once you set a type, it can never be changes. Oh sure, you can cast it, but that’s just the type being temporarily converted. The original data stays with the original type.

So, if we’re building a program, and given a choice, which would you prefer to do?

  • Write a program quickly
  • Write a program that runs fast
  • Write a program that has few if any bugs
  • Write a program that you can read and make sense of latter
  • Write a program that runs on many different devices

This partially drives our choice of language.