Skip to content
ExamSpine

Lesson 1.7

Four basic types

Part 1: Programs that talkReading, about 4 min1 exercise in this lesson

Four basic types

By the end of this you will know the four basic types every program uses, and be able to choose the right one for a given value.

Every value in a program has a type. The type decides what the value can hold and what you can do with it. There are four types you will use from the start.

The four types

What it holdsPython nameJava nameExample
A whole numberintint3, 0, -7
A number with a fractionfloatdouble4.75, 0.0, -2.5
TextstrString"Tea", "Floor 3"
True or falseboolbooleanTrue / true, False / false

In Python, the type is decided by the value itself: 3 is an int, 4.75 is a float, "Tea" is a str, True is a bool. You do not write the type name when you create a variable.

In Java, you write the type when you first declare a variable.

public static void main(String[] args) {
    int count = 3;
    double price = 4.75;
    String name = "Tea";
    boolean available = true;
}

Choosing a type

The question to ask: what kind of value is this?

  • A count, a position, an age: int (whole number).
  • A measurement, a temperature, an average: float in Python, double in Java (number with a fraction).
  • A name, an address, a message: str in Python, String in Java (text).
  • A yes or no question: bool in Python, boolean in Java (true or false). "Is the door open?" is a boolean; the door's floor number is an int.

A common mistake: choosing a type by the word, not the value. "Rating" sounds like a number, but a rating of exactly 1 to 5 stars with no half stars is an int. A rating that can be 4.25 is a float in Python and a double in Java.

Another common mistake: putting a number inside quotes. "3" is text, not a whole number. Adding 1 to it does not give 4: Python stops with an error, and Java joins the two and gives 31. To add, you first convert the text into a number (the next lesson). 3 without quotes is an int.

Now try it yourself on the questions below.

Exercise 1.7.11.7.1 · Answer itData types

A library program stores three values about each book. Identify the most suitable data type for each value.

(a) the number of times the book has been borrowed

(b) the book's average star rating, such as 4.25

(c) whether the book is currently on loan

[3]