Thuta Learning
Java
BasicProgrammingBeginner

Data Types

JavaLesson 625 min

What you'll walk away with

  • Name the eight primitive types and choose a suitable type for each piece of data
  • Explain that a primitive holds its value directly while a reference type points to an object
  • Predict the results of expressions like `7 / 2`, `(int) 9.99` and `Integer.MAX_VALUE + 1`
  • Use the `L` and `f` suffixes and single versus double quotes correctly

Explain it simply

Data types in plain words

A data type says what kind of value something is, how much memory it takes and what you can do with it. Whole numbers go in an `int`, decimals in a `double`, a single character in a `char`, true/false in a `boolean`, and text in a `String`.

Calculations are only right when the types are right. If you never do maths with a phone number, for example, a `String` suits it better than an `int`: the leading `0` is not lost and there is no limit on the number of digits.

Problem → Why → Solution

The problem: data poured into the wrong type

Say you are writing order data for an online shop. You put the phone number in an `int`, the price `19.99` in an `int`, and write the grade `A` in double quotes. None of the three lines compiles.

That is the lucky case. More dangerous is code that compiles and gives wrong answers: dividing two `int`s drops the decimals, and going past the `int` limit wraps around to a negative number, all without a single error.

Main.java
public class Main {
    public static void main(String[] args) {
        int phone = 959123456789;  // error: integer number too large
        int price = 19.99;         // error: possible lossy conversion from double to int
        char grade = "A";          // error: String cannot be converted to char

        int views = 2_000_000_000 + 2_000_000_000;  // compiles! but is -294967296
    }
}

Why it matters

Every type has a fixed size. An `int` is 32 bits, so it holds at most 2,147,483,647, and going past that wraps around to the negatives. The compiler catches only literals that are certainly wrong; it does not check values computed at run time, so choosing the type is your job.

Core concept: primitives and references

Java types fall into two big groups. The eight primitive types store the value directly in the variable: after `int x = 5;`, the number 5 itself sits in `x`. Reference types (`String`, arrays, classes you write) keep the object elsewhere in memory, on the heap, and the variable holds only a reference that points to it. A reference variable can be `null`, pointing at nothing, but a primitive can never be `null`.

TypeSize / rangeExample
`byte`, `short`8-bit (-128..127), 16-bitFile bytes, sensor readings
`int`32-bit, about ±2.1 billionQuantity, age, score
`long`64-bit, `L` suffix`3_000_000_000L`, IDs, timestamps
`float`, `double`32/64-bit decimals, `f` for `float``1.5f`, `19.99`
`char`16-bit single character, single quotes`'A'`
`boolean``true` or `false``isAvailable`

Literals have default types too. A whole-number literal such as `42` is an `int`, and a decimal literal such as `19.99` is a `double`. That is why a big literal for a `long` needs an `L` at the end, and a `float` needs an `f`.

There are two directions of conversion. Widening (`int` → `long` → `double`) loses nothing, so it happens automatically. Narrowing (`double` → `int`) can lose information, so you must write a cast such as `(int) 9.99` yourself, and it truncates rather than rounds, giving `9`. Dividing two `int`s also produces an `int`, so `7 / 2` is `3`.

The difference between primitives and references shows up in assignment. Writing `int b = a;` copies the value of `a` into `b`, so changing `b` later leaves `a` untouched. Assigning one reference variable to another copies only the pointer, not the object, so both variables then point to the same object. You rarely notice this with `String`, because String objects are immutable, but it matters a great deal for arrays and your own classes, which you will meet in later lessons.

How to pick a type
  1. Number, text or yes/no?
  2. Will you do maths with it?
  3. How large can it ever get?
  4. Do decimals need to be exact?

No maths: `String`. Whole numbers: `int` (or `long` if huge). Decimals: `double` (money: `BigDecimal`). Yes/no: `boolean`.

General pattern: types and literals

java
int whole = 42;              // integer literals are int
long big = 9_000_000_000L;   // L for long, _ for readability
double decimal = 3.14;       // decimal literals are double
float small = 3.14f;         // f for float
char letter = 'X';           // single quotes: exactly one character
boolean flag = true;         // true or false only
String text = "any text";    // double quotes: a String object

int narrowed = (int) decimal; // explicit cast: drops the .14

Primitive types are written in lower case, while `String` is a class and takes a capital S. Single quotes are for a `char`, double quotes for a `String`. A narrowing conversion needs an explicit `(type)` cast.

An order stored with several types

The program below stores the data for a keyboard order using six different types. Before running it, predict whether the last line, `Full pairs:`, shows `1.5` or `1`.

Main.java
public class Main {
    public static void main(String[] args) {
        int quantity = 3;
        double price = 19.99;
        char grade = 'A';
        boolean isAvailable = true;
        String productName = "Keyboard";
        long yearlyViews = 3_000_000_000L;

        System.out.println(productName + " x " + quantity);
        System.out.println("Total: " + (quantity * price));
        System.out.println("Grade: " + grade);
        System.out.println("Available: " + isAvailable);
        System.out.println("Yearly views: " + yearlyViews);
        System.out.println("Full pairs: " + (quantity / 2));
    }
}

Code breakdown

  1. A char in single quoteschar grade = 'A';

    A `char` holds exactly one character, in single quotes. Writing `"A"` makes it a String and gives 'String cannot be converted to char'.

  2. A long literallong yearlyViews = 3_000_000_000L;

    Three billion is larger than the `int` maximum (about 2.1 billion), so it needs a `long`. Without the `L`, the literal is read as an `int` and fails with 'integer number too large'. The `_` is only there for readability.

  3. int times doubleSystem.out.println("Total: " + (quantity * price));

    Multiplying an `int` by a `double` first widens the `int` to a `double`, so the result is a `double`. The parentheses make the multiplication happen before the text is joined.

  4. Integer divisionSystem.out.println("Full pairs: " + (quantity / 2));

    Both `quantity` and `2` are `int`, so the result is an `int`: the .5 of 1.5 is dropped and you get `1`. Here, where we want only complete pairs, that happens to be exactly the answer we need.

You should see
Keyboard x 3
Total: 59.97
Grade: A
Available: true
Yearly views: 3000000000
Full pairs: 1

Surprises at the edges

Run the program below. Every line compiles and no error appears, yet some results will differ from what you expect. On overflow Java does not throw an exception; the value wraps around. And because a `double` is stored in binary, some decimals such as `0.1` cannot be stored exactly.

Main.java
public class Main {
    public static void main(String[] args) {
        System.out.println(7 / 2);                  // 3
        System.out.println(7 / 2.0);                // 3.5
        System.out.println((int) 9.99);             // 9
        System.out.println(Integer.MAX_VALUE + 1);  // -2147483648
        System.out.println(0.1 + 0.2);              // 0.30000000000000004
        System.out.println('A' + 1);                // 66
    }
}

The last line is interesting: a `char` is a number (its Unicode code) underneath, so `'A' + 1` is an `int`, `66`. Every primitive also has a wrapper class, such as `Integer`, `Double` and `Character`, and Java converts between them automatically when needed (autoboxing). A wrapper can be `null`, and turning a `null` `Integer` into an `int` throws a `NullPointerException`.

In real projects

In real data models

Type choice matters in every app data model: e-commerce orders, student grades, booking status, payment amounts. Database IDs are stored as `long`, because real systems have outgrown the `int` limit of 2.1 billion rows. 'Numbers' you never do maths with, such as phone numbers, postcodes and ID-card numbers, are stored as `String`.

Money avoids `double`. Computing `1.10 - 1.00` with `double` gives `0.10000000000000009`, and accounting cannot be off by even a cent. Banks and payment systems use `java.math.BigDecimal`, or store amounts in a `long` as a count of cents. Keeping Java types in line with database column types (`INT`, `BIGINT`, `DECIMAL`) also protects against losing data. In code review, reviewers often question the type of every new field: how large can this value get, and do its decimals need to be exact?

Common mistakes

Common data type mistakes

Computing an average with two ints

With `int total = 254; double avg = total / 3;`, `avg` is `84.0`, not `84.666...`. The right side is computed as `int / int` first, losing the decimals, and only then stored in the `double`. Write `total / 3.0` or `(double) total / 3`.

Expecting Java to warn about overflow

When an `int` calculation goes out of range, Java does not throw an exception; it wraps around to a negative number. Use `long` for values that can grow large, such as view counts or amounts, or use `Math.addExact`, which throws an exception on overflow.

Using the wrong kind of quotes

`'A'` is a `char`; `"A"` is a `String`. Putting two characters in single quotes, as in `'AB'`, gives an 'unclosed character literal' error.

Mini challenge

Mini challenge: a score average

Store three subject scores (85, 90, 79) in `int`s, then print the total, the average from integer division, the real average, a grade (`char`) and whether the student passed (`boolean`).

  • Use `int` for the scores and the total
  • Store the result of `total / 3` in an `int` variable
  • Compute the real average as a `double` without losing the decimals
  • Store the grade as a `char` in single quotes and the pass result as a `boolean`
Average.java
public class Average {
    public static void main(String[] args) {
        // TODO: three int scores: 85, 90, 79
        // TODO: int total of the three scores

        // TODO: int truncated = total divided by 3 (integer division)
        // TODO: double average that keeps the decimals
        // TODO: char grade 'B' and boolean passed (average >= 50)

        // TODO: print Total, Integer division, Real average, Grade and passed
    }
}

Expected: Four lines: `Total: 254`, `Integer division: 84`, `Real average: 84.66666666666667` and `Grade: B, passed: true`.

Show hint

To keep the decimals, at least one side of the division must be a `double`: `total / 3.0`.

Show solution
Average.java
public class Average {
    public static void main(String[] args) {
        int math = 85;
        int science = 90;
        int english = 79;
        int total = math + science + english;

        int truncated = total / 3;
        double average = total / 3.0;
        char grade = 'B';
        boolean passed = average >= 50;

        System.out.println("Total: " + total);
        System.out.println("Integer division: " + truncated);
        System.out.println("Real average: " + average);
        System.out.println("Grade: " + grade + ", passed: " + passed);
    }
}

Quick quiz 1 / 3

What does `System.out.println(7 / 2);` print?

Quick quiz 2 / 3

Which declaration compiles?

Quick quiz 3 / 3

What does `double d = 7 / 2; System.out.println(d);` print?

What to remember

  • The eight primitives hold values directly; reference types like `String` point to objects
  • Whole-number literals are `int` and decimal literals are `double`, so add `L` for `long` and `f` for `float`
  • `int / int` drops the decimals, and an `(int)` cast truncates rather than rounds
  • Overflow wraps around without an error, and `double` is not exact enough for money

Java Language Specification, Java SE 25 — Oracle

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Data Types | Thuta Learning