انتقل إلى المحتوى
أمين أبوزيد
منشورBEG-009-L02

الأنواع الأولية الثمانية

  • الدرس 2 من 7
  • 12 دقيقة قراءة
  • مبتدئ
في هذا الدرس 11 موضوعات

هذا الدرس متاح حاليًا باللغة الإنجليزية فقط، ولم تُنشر نسخته العربية بعد.

Lesson Overview

In Lesson 1 a variable was a labeled box with a type. This lesson looks at the simplest boxes Java offers: the eight primitive types. Each one is built for one kind of data and has a fixed size, which decides the range of values it can hold. Picking the right one is the first real design decision in every program.

Think of boxes of different sizes. A shoebox, a suitcase, and a shipping container can all hold "stuff", but you would not ship a sofa in a shoebox, and you would not use a container to carry a single key. Choosing a type is choosing the box that fits the data.

Why this matters: a wrong type causes bugs that look like wrong answers rather than crashes. A price stored as a decimal that cannot hold decimals exactly, or an id stored in a box too small for it, silently produces bad data. Backend work is full of ids, counts, prices, flags, and dates, and each needs a deliberate type.

This lesson builds on Lesson 1 (declaring and assigning variables). It does not need conversions yet; those come in Lesson 5.

Learning Objectives

By the end of this lesson you will be able to:

  • Name the eight primitive types and group them into whole numbers, decimals, characters, and true/false.
  • Declare and initialize a variable of each primitive type.
  • Choose int by default for whole numbers, long for very large ones, and double by default for decimals.
  • Say roughly what range int covers and read exact ranges from Integer.MIN_VALUE and Integer.MAX_VALUE.
  • Explain why double is the wrong choice for money and what to use instead, for now.
  • Tell 'A' (a char) from "A" (a String).

Written Explanation

The eight types

A primitive type holds a simple value directly in the box. Java has exactly eight:

GroupTypeSizeHoldsExample
Whole numbersbyte8 bits-128 to 127byte level = 12;
short16 bits-32,768 to 32,767short year = 2026;
int32 bitsabout -2.1 billion to 2.1 billionint age = 29;
long64 bitsabout -9.2 quintillion to 9.2 quintillionlong population = 8_000_000_000L;
Decimalsfloat32 bitsdecimal numbers, less precisefloat ratio = 0.75f;
double64 bitsdecimal numbers, more precisedouble temperature = 36.6;
Characterchar16 bitsone characterchar initial = 'A';
True/falsebooleannot precisely definedtrue or falseboolean isStudent = true;

A bit is one binary digit (Module 1); the more bits a box has, the more different values it can hold. For the whole-number types the sizes and ranges above are fixed by the language. The Java tutorial says the exact size of boolean is not precisely defined, which is why the table does not give one.

You do not have to memorize the ranges. Java will tell you:

java
System.out.println(Integer.MIN_VALUE);
System.out.println(Integer.MAX_VALUE);

The same names exist as Byte, Short, and Long.

Whole numbers: int first

For whole numbers, use int unless you have a reason not to. It is the default whole-number type of the language: the literal 42 is an int. It covers a little over two billion in each direction, which is enough for ages, quantities, counts, and most ids.

  • long is for values that can exceed that, such as a population, a count of milliseconds, a file size in bytes, or a database id that may grow past two billion. A long literal ends in L: 8_000_000_000L. (The underscores in number literals are only for readability, and Lesson 4 returns to them.)
  • byte and short exist mainly for saving memory in large collections of numbers, or for making a limited range obvious. For a single variable they add little, and they cause extra conversion work (Lesson 5). Beginners should rarely reach for them.

Decimals: double first

For numbers with a fractional part, use double. A decimal literal such as 36.6 is a double. float uses half the memory but is less precise; to write a float literal you must add f, as in 0.75f. Unless you have a specific reason, choose double.

Both are approximations. They store numbers in binary, and many everyday decimals such as 0.1 have no exact binary form, in the same way 1/3 has no exact decimal form. That is harmless for temperatures and measurements, but it matters for money, as the next section shows.

One character: char

A char holds a single character written in single quotes: 'A', '7', '!'. Do not mix up the quote styles:

  • 'A' is a char, one character.
  • "A" is a String, text (even though it has one letter). Lesson 3 covers String.

Internally a char is a 16-bit number, so it also behaves like a number in arithmetic. You will see a small taste of that below, and the full story in Lesson 5.

True or false: boolean

A boolean holds exactly true or false, in lowercase. It is the type for yes/no facts: isStudent, hasPaid, isEmpty. Later modules use boolean to make decisions with if. A boolean is not a number in Java: you cannot store 1 in it.

Why not double for money?

Run this in your head: what is 0.1 plus 0.2? Mathematics says 0.3. A double says:

text
0.30000000000000004

That tiny error is not a bug in Java. It is how binary decimals work. A tiny error per operation adds up and breaks comparisons such as 0.1 + 0.2 == 0.3, which is false.

For money, the Java tutorial's advice is blunt: do not use float or double for currency, and use BigDecimal from the standard library. We have not learned objects yet, so for this module the practical beginner method is to store money in the smallest unit as a whole number: cents in an int (or a long for big totals). Then 19.99 is stored as 1999, and all arithmetic is exact integer arithmetic. BigDecimal and the database type for money come in later modules.

Examples

Example 1: one variable of each kind (simple)

java
public class Primitives {
    public static void main(String[] args) {
        int age = 29;
        long population = 8_000_000_000L;
        double temperature = 36.6;
        float ratio = 0.75f;
        char initial = 'A';
        boolean isStudent = true;
        byte level = 12;
        short year = 2026;
        System.out.println(age + " " + population + " " + temperature + " " + ratio
            + " " + initial + " " + isStudent + " " + level + " " + year);
    }
}

Output (JDK 21):

text
29 8000000000 36.6 0.75 A true 12 2026

Read each declaration as "this is the box that fits this data". The names say what is inside; the types say what shape the data has.

Example 2: checking the limits (practical)

java
public class Limits {
    public static void main(String[] args) {
        System.out.println("byte:  " + Byte.MIN_VALUE + " to " + Byte.MAX_VALUE);
        System.out.println("short: " + Short.MIN_VALUE + " to " + Short.MAX_VALUE);
        System.out.println("int:   " + Integer.MIN_VALUE + " to " + Integer.MAX_VALUE);
        System.out.println("long:  " + Long.MIN_VALUE + " to " + Long.MAX_VALUE);
    }
}

Output:

text
byte:  -128 to 127
short: -32768 to 32767
int:   -2147483648 to 2147483647
long:  -9223372036854775808 to 9223372036854775807

When you wonder "will this number fit?", compare it with these values. A phone number such as 5551234567 is larger than Integer.MAX_VALUE, so it would not fit in an int. (Phone numbers are better stored as text anyway, because you never do arithmetic on them.)

Example 3: money as cents, and a char that acts like a number (realistic)

java
public class Cart {
    public static void main(String[] args) {
        System.out.println(0.1 + 0.2);
        System.out.println(0.1 + 0.2 == 0.3);

        int priceCents = 1999;
        int totalCents = priceCents * 3;
        System.out.println("Total: " + totalCents / 100 + "." + totalCents % 100);

        char letter = 'A';
        System.out.println(letter);
        System.out.println(letter + 1);
        System.out.println((char) (letter + 1));
    }
}

Output:

text
0.30000000000000004
false
Total: 59.97
A
66
B

The first two lines show double imprecision. The cart part keeps the price as 1999 cents; / 100 gives the whole currency units and % 100 the remaining cents. (This simple printing is only correct while the cents part is two digits: 5905 cents would print 59.5. Proper formatting is a later topic.)

The last three lines hint at what char really is: letter + 1 is the number 66, because 'A' is stored as the number 65. Converting it back with (char) gives B. The cast (char) is explained in Lesson 5; for now notice only that a char is a number underneath.

Backend Insight

Type choice shows up in real systems everywhere:

  • Ids and counters. A database table that gets millions of rows a day will outgrow int ids (about 2.1 billion). Services often use long ids from the start. Choosing int for something that can grow is a classic production bug that is expensive to fix later, once data exists.
  • Money. Services that handle payments store amounts either as whole minor units (cents) in an integer type, or use BigDecimal in Java with a decimal type such as numeric in the database. They never use floating point for balances. This is why the course returns to BigDecimal later.
  • Time. Timestamps are frequently stored as a count of milliseconds, which needs a long: the int range would run out in about 24 days of milliseconds (2,147,483,647 ms is a little under 25 days).

The principle: choose the type from the data's meaning and its largest realistic value, not from habit.

Common Mistakes

Mistake 1: Using double for money

double price = 19.99; looks fine, but sums and comparisons may be off by tiny fractions. Prefer whole cents in an int or long for now, and BigDecimal once it is introduced.

Mistake 2: A whole-number literal that is too large

java
long big = 5000000000;

The compiler (JDK 21) says:

text
L2C.java:4: error: integer number too large
        long big = 5000000000;
                   ^

A plain whole-number literal is an int, even when the variable is a long. The literal itself must fit in an int unless it carries the L. Fix: long big = 5000000000L;.

Mistake 3: Mixing up 'A' and "A"

char c = "A"; is rejected with incompatible types: String cannot be converted to char. Single quotes for one character, double quotes for text.

Mistake 4: A number that does not fit the type

byte b = 200; fails with incompatible types: possible lossy conversion from int to byte, because 200 is outside -128 to 127. Pick a larger type, or reconsider the data.

Mistake 5: Treating boolean like a number

boolean ok = 1; produces incompatible types: int cannot be converted to boolean. Use true or false.

Exercises

Try each exercise yourself before opening the solutions.

Level A: Foundation

A1. Which of the eight types would you choose for each: the number of seats in a bus, the speed of a car in 0.1 km/h units, whether a door is locked, the grade letter B?

أظهر الحل A1

A1. Seats: int. Speed: double, since it is a measurement with a fractional part. Door locked: boolean. Grade letter: char.

A2. What is the difference between '7' and 7 and "7"?

أظهر الحل A2

A2. '7' is a char, the character seven. 7 is an int, the number seven. "7" is a String, text containing the digit seven. Only the int can be used for normal arithmetic.

A3. Which is the default type for a decimal literal like 2.5, and what must you add to write it as a float?

أظهر الحل A3

A3. A decimal literal is a double. To write a float literal add f (or F): 2.5f.

Level B: Application

B1. Write one declaration with an initial value for each: the year 1999, the number of bytes in a 3 GB file (3 billion), a price of 25.50 stored safely for a shop, and whether a user is subscribed.

أظهر الحل B1

B1.

java
int year = 1999;
long fileBytes = 3_000_000_000L;
int priceCents = 2550;
boolean isSubscribed = true;

Three billion is larger than Integer.MAX_VALUE, so it needs long and an L on the literal. The price is kept in cents as a whole number.

B2. Name the problem, without compiling: short year = 70000;. Then say what to change.

أظهر الحل B2

B2. 70000 is outside the short range (-32,768 to 32,767), so the compiler reports a lossy conversion from int to short. Use an int, or reconsider the data: 70000 is not a realistic year.

B3. A game awards 50 points for each of 4 coins. Write the points in an int, print Points: and the total. Then say what you would change if the player could collect 100 million coins.

أظهر الحل B3

B3.

java
int points = 50 * 4;
System.out.println("Points: " + points);

It prints Points: 200. With 100 million coins the total of 5 billion exceeds the int range, so the variable should be a long, and the arithmetic written so that it is done as long (Lesson 5 explains how).

Level C: Challenge

C1. Predict the output of System.out.println('B' + 1); and System.out.println("B" + 1);. Explain why they differ.

أظهر الحل C1

C1. The first prints 67: 'B' is a char, which is stored as the number 66, and adding the int 1 gives the number 67. The second prints B1: "B" is a String, so + joins text. The type of the left operand decides what + does.

C2. A teammate proposes storing the total of all payments of a bank in a double "because it has decimals and a big range". List two concrete problems with that, and propose a better design for now.

أظهر الحل C2

C2. Problems: rounding errors can accumulate over many additions, so the total may not match the individual amounts, and equality checks may fail. Better for now: store every amount as whole cents in a long, so all arithmetic is exact; later use BigDecimal (and numeric in the database).

Mini Challenge

Design the data for a small shop item. Write variable declarations, with sensible names and initial values, for: the item's id (assume it could one day pass three billion), its name, its price (stored safely), the stock quantity, the one-letter size code, and whether it is on sale. Then print the item in one line.

Check your work: every variable uses the type that best fits the data and its largest realistic value; the price is not a double; the id uses a long literal with an L; the size code uses single quotes; the program compiles and the output line is readable.

Summary & Next Lesson

Key takeaways

  • Java has eight primitive types: byte, short, int, long (whole numbers), float, double (decimals), char (one character), and boolean (true/false).
  • Default choices: int for whole numbers, long when values can pass about two billion, double for decimals.
  • Integer.MIN_VALUE and Integer.MAX_VALUE (and the matching names for the other types) give exact limits.
  • 'A' is a char, "A" is a String.
  • Do not use double for money: store whole cents in int or long for now.

Next lesson

You have used String informally. The next lesson, "Strings and reference types", explains what String is, why it is not a primitive, and what that means for how the box holds its value.

Self-check

  1. Which type is the default for whole numbers, and which for decimals?
  2. What must a long literal and a float literal end with?
  3. Which of 'x' and "x" is a char?
  4. Why is 0.1 + 0.2 == 0.3 false for doubles?
  5. How can you store 12.75 safely for money without double?
أظهر الإجابات
  1. int for whole numbers; double for decimals.
  2. L for long (such as 5L), and f for float (such as 0.5f).
  3. 'x', with single quotes, is the char.
  4. Doubles are stored in binary, and 0.1 and 0.2 cannot be stored exactly, so the sum is slightly different from 0.3.
  5. As 1275 cents in an int or long.

References

  • Oracle, The Java Tutorials: Primitive Data Types. It lists the eight primitive types with sizes and ranges, says that int and double are the usual defaults, says that float/double should not be used for precise values like currency (use BigDecimal), and says that the size of boolean is not precisely defined.
  • Oracle, The Java Language Specification, Java SE 21, Chapter 4: Types, Values, and Variables. It gives the exact integral ranges, says char is an unsigned 16-bit value, says floating-point types follow IEEE 754, and describes how integer operators wrap around on overflow.
  • All programs and messages above were compiled and run with JDK 21. Other versions may word messages differently. The "about 25 days" milliseconds figure is simple arithmetic from the int maximum. The remark that other languages using IEEE 754 doubles show the same 0.1 + 0.2 result was not checked against a source.

التطبيق

طبّق هذا الدرس بمختبر الوحدة وتمارينها واختبارها.

المختبر والتمارين الاختبار

تعليم الدرس كمكتمل اختياري ويمكنك التراجع عنه في أي وقت. يبقى تقدمك محفوظًا في هذا المتصفح.

اكتب للبحث في المستويات والمراحل والوحدات والدروس.