Skip to content

Data Types



Why Do We Need Data Types?

Analogy

A bank application form has an Age box that expects a whole number, a Name box that expects letters, an Initial Deposit box that allows decimals, and a passport question that wants yes or no.

You fill that in without thinking, because you recognise the different kinds of information. A computer needs the same classification, but the rules have to be stated explicitly. Before a program can store or work with anything, it has to be told what kind of value it is holding.


What Is a Data Type?

Definition

A data type is an attribute that tells the computer how to interpret a piece of data.

It answers three questions:

  1. Meaning — is this a number, text, or a true/false condition?
  2. Operations — what does + do here: arithmetic, or joining text?
  3. Storage — how much memory does this value need?
Code
int age = 24;

int is the type, age is the variable, and 24 is the value. These three words are often used loosely, and keeping them apart makes the rest of this chapter easier.


How Data Is Represented in Memory

Memory holds only bits, which are sequences of 0 and 1. The bits carry no record of what they mean.

The same thirty-two bits are a whole number, a decimal, or four letters, depending only on how they are read. Nothing about the bits changed between the three answers.

That is the idea the rest of the chapter rests on: the type is what gives the bits meaning.


Primitive Data Types

Almost every language provides the same four building blocks. Each holds one simple value.

  • Integer — whole numbers with no decimal point, for counting, indexes and quantities: 7, 0, -25
  • Floating-point — numbers with a fractional part, for measurements and averages: 3.14, -0.5
  • Character — a single symbol, stored as a number through an encoding such as ASCII or Unicode, so 'A' is really 65
  • Boolean — a logical state with exactly two values, used for every decision a program makes: true, false
Code
int      age      = 24;double   salary   = 45000.50;char     grade    = 'A';boolean  isPlaced = true;

Note

Do not use floating-point types for money. The reason is in Common Mistakes below.


Strings

A string is a sequence of characters grouped into text. If a character is a single Scrabble tile, a string is the whole word on the board.

"Hello, World!" is a string. "A" is also a string, one letter long but still text, and not the same as the character 'A'. "" is an empty string: zero characters, and still perfectly valid data.

In Java and Python, strings are immutable. Changing a string does not edit it in place; it builds a new string and points the variable at that. This matters for performance when text is modified inside a loop.


Composite Data Types

Composite types are built by grouping values together.

  • Arrays and lists — ordered collections: [10, 20, 30, 40]
  • Tuples — fixed groups that cannot be changed: (40.7128, -74.0060) for a coordinate
  • Maps or dictionaries — key and value pairs: {"name": "Alice", "age": 25}
  • Sets — unordered collections that drop duplicates: {1, 2, 3}

Each of these becomes a chapter of its own in Data Structures. For now the distinction is enough: primitive types hold one value, composite types organise many.


Size and Range

Every type comes with physical boundaries in memory.

Size is how many bytes the system reserves. A standard integer is usually 4 bytes, or 32 bits. Range is the span of values that fits in that size, so a 32-bit signed integer holds -2,147,483,648 to 2,147,483,647. Representation is how the value is encoded: two's complement for signed integers, IEEE 754 for floating-point.

Exact sizes are decided by the language, so never assume a size carries across from one language to another.


Static and Dynamic Typing

Languages differ in when types are checked.

Static typing, as in Java and C++, means the type is declared up front and cannot change. Mistakes are caught at compile time, before the program runs.

Dynamic typing, as in Python and JavaScript, means the type is taken from the value, and the variable can hold a different type later. The check happens while the program runs.

CodeJava, static
int age = 25;age = "Hello";   // compile error, the program will not build
CodePython, dynamic
age = 25age = "Hello"    # valid, the variable now refers to text

Static typing trades flexibility for safety. Dynamic typing trades safety for speed of writing. Dynamically typed languages still have types; what changes is when they are checked.


Type Conversion

Implicit conversion happens automatically when it is safe. In 5 + 2.0, the integer 5 is widened to 5.0 and the result is 7.0.

Explicit conversion, or casting, is when you force it, usually because data may be lost.

CodeJava
int rounded = (int) 3.9;              // 3, the fraction is removedint n = Integer.parseInt("42");       // 42String s = String.valueOf(42);        // "42"
CodePython
int(3.9)      # 3int("42")     # 42str(42)       # "42"int("hello")  # ValueError, there is no number here

Truncation is the detail people get wrong most often. A cast to an integer chops the fraction off rather than rounding, so (int) 3.9 is 3, not 4.


Special Values

A program regularly needs to represent nothing at all, and each language spells it differently.

LanguageKeyword
Java, C#null
C++nullptr
PythonNone
JavaScriptnull for intentional absence, undefined for never assigned
The absence of a value is itself a value, with a name.

These are not the same as an empty value. 0 is a number, "" is text containing zero characters, and null is the absence of any value at all.


Common Mistakes

Watch out

Integer overflow. Adding 1 to the largest value an integer can hold usually does not crash. It wraps round to the most negative value, like an odometer rolling from 999999 to 000000.

Floating-point precision. Many decimals have no exact binary representation, so 0.1 + 0.2 gives 0.30000000000000004. Never test two floating-point values for exact equality; test whether the difference between them is very small. This is also why money is stored in integer cents or a decimal type.

Integer division. When both operands are integers, many languages discard the fraction. In Java and C++, 7 / 2 is 3. Python's / gives 3.5, and 7 // 2 gives 3. It depends on the operand types, not on the language alone.

Character against string. In statically typed languages 'A' in single quotes is a character, a number underneath, while "A" in double quotes is text. They are not interchangeable.

Number against numeric string. 5 + 5 is 10. "5" + "5" is "55".


Data Types and Data Structures

A data type describes a single value, such as an integer or a string. A data structure is the arrangement that organises many values for efficient access, such as an array, a tree or a graph.

Data types are the bricks. Data structures are the house.


Data Types Across Languages

ConceptJavaC++PythonJavaScript
Integerbyte, short, int, longint, long longint, arbitrary precisionNumber, BigInt
Decimalfloat, doublefloat, doublefloatNumber
Characterchar, UTF-16charNo separate typeNo separate type
Booleanbooleanboolboolboolean
Empty valuenullnullptrNonenull, undefined
The same concepts, named and sized differently in each language.

Two differences are worth remembering. A Python integer grows as large as memory allows, while a Java int is capped at 32 bits. And JavaScript has no separate integer type at all: every Number is a double-precision float underneath.


Quick Check

  1. What is the difference between 5 and "5"?
  2. Why might 0.1 + 0.2 not equal 0.3?
  3. Is null the same as 0?
  4. In Java, what happens if you write int score = "High";?
Show answer
  1. 5 is a numeric value you can do arithmetic on. "5" is text containing the character 5, so + joins it rather than adding.
  2. 0.1 and 0.2 have no exact binary representation, so the stored values are slightly off and the error shows up in the result.
  3. No. 0 is a real numeric value. null means no value is present at all.
  4. It fails to compile. Java is statically typed, so the mismatch is caught before the program is allowed to run.

Quick Recap

  • A data type tells the computer how to interpret raw bits in memory
  • The primitives are integers, floating-point numbers, characters and booleans
  • A string is a sequence of characters, and is immutable in Java and Python
  • Arrays, lists, maps and sets group multiple values together
  • Static typing locks a variable to one type; dynamic typing lets it change
  • Conversion is implicit when it is safe, and explicit when data may be lost
  • Watch for integer overflow, floating-point approximation, and mixing text with numbers
  • Data types describe values; data structures organise them

Where This Leads

You now know how a computer classifies data. The next step is storing those values somewhere the program can reach them, which means named locations in memory.

Data Types → Variables → Operators → Conditions → Loops → Functions → Memory → Data Structures

Key takeaway

A data type is not the data itself. It is the instruction that tells the computer how to read, store and operate on that piece of data.