Õppetund 10/140
Kirjalik õppetund · 15 min

Primitive Data Types

Work with Java's eight primitive types, choose between `int`, `long` and `double`, and understand literal suffixes, overflow and floating-point limits.

Eelvaade

Vaatad tasuta eelvaate õppetundi.

Lesson Overview

In Java, every variable stores a specific type of value: a whole number, a decimal number, a character, or true or false. To represent these basic values, Java provides eight primitive data types.

Choosing the type is a real decision, not a formality. Pick one that is too small and a large number silently turns negative; use a decimal type for money and a price is off by a fraction of a paisa; divide two whole numbers and the decimal part disappears. In this lesson, we look at each primitive type, its range, how its values are written, and which one to choose for which job.

Learning Objectives

After completing this lesson, you will be able to:

  • Explain what a primitive data type is
  • Identify Java's eight primitive types
  • Select an appropriate integer type for whole numbers
  • Understand the difference between float and double
  • Use char and boolean
  • Understand why L and F suffixes are needed
  • Use underscores in numeric literals
  • Understand the basic concept of integer overflow
  • Explain floating-point precision limitations
  • Select the appropriate primitive type based on the requirement

What Is a Data Type?

A data type determines what kind of value a variable can store:

java
int age = 30;
double averageMark = 85.5;
boolean isAvailable = true;

Here, int indicates that age will store an integer value, double stores a decimal value, and boolean stores a logical state. A value written directly in source code, such as 30, 85.5, 'A' or true, is called a literal.

What Is a Primitive Data Type?

A primitive data type is a built-in fundamental type in the Java language. Primitive types are not objects; they represent basic values, like the three variables above. Java's eight primitive types can be divided into four categories:

CategoryTypes
Integerbyte, short, int, long
Floating-pointfloat, double
Characterchar
Booleanboolean

Primitive Types at a Glance

TypeSizeExampleCommon Use
byte8 bits100Very small integers or binary data
short16 bits1200Small integers
int32 bits5000General whole numbers
long64 bits8_000_000_000LLarge whole numbers
float32 bits10.5FLower-precision decimals
double64 bits10.5General decimal calculations
char16 bits'A'A single UTF-16 code unit
boolean—trueTrue/false state

The Java language does not define a fixed storage size for boolean, so there is no need to memorize a specific bit size for it.

Integer Types

Java's integer primitive types are byte, short, int and long. These types store whole numbers without a decimal part, such as -20, 0, 25, 1000 or 5000000.

byte

byte is an 8-bit signed integer with the range -128 to 127:

java
byte percentage = 100;
byte temperature = -10;

A value outside this range cannot be stored directly, so byte value = 128; will not compile. byte is not commonly needed for general application data. It is useful for raw binary data such as the bytes of a file or a network message, for very large arrays where memory matters, and for external formats that require 8-bit values.

short

short is a 16-bit signed integer with the range -32,768 to 32,767. It is also not commonly used in general Java applications:

java
short roomNumber = 1200;
short maximumScore = 30000;

int

int is a 32-bit signed integer with the range -2,147,483,648 to 2,147,483,647. For general whole numbers, int is the most common choice in Java: ages, quantities, marks, page numbers, lesson counts, inventory counts and other counters.

java
int age = 30;
int studentCount = 500;
int lessonCount = 120;

long

long is a 64-bit signed integer with the range -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Use long for whole numbers that are larger than the int range:

java
long totalUsers = 5_000_000_000L;
long fileSizeInBytes = 8_000_000_000L;

Use an uppercase L at the end of large long literals, as in long population = 8_000_000_000L;. L tells the compiler that the literal is a long. Although lowercase l is technically allowed, avoid it, because it can look similar to the digit 1: 100l reads like 1001, while 100L cannot be misread.

Choosing an Integer Type

Practical rule: use int for general whole numbers, long when the int range is not enough (such as 5 billion platform users), and byte or short only when there is a specific reason.

Underscores in Numeric Literals

Underscores can be used between digits to make large numbers easier to read, as in int oneMillion = 1_000_000; or 8_000_000_000L. The compiler ignores these underscores, so int value = 1_000; and int value = 1000; represent the same value.

Integer Division

When two integers are divided, the result follows integer arithmetic, so the result is 2, not 2.5:

java
int result = 5 / 2;
System.out.println(result);

Output:

text
2

To get a decimal result, at least one operand must be floating-point:

java
double result = 5.0 / 2;
System.out.println(result);

Output:

text
2.5

Integer Overflow

If the result exceeds the maximum range of an integer type, overflow can occur:

java
int value = 2_147_483_647;
value = value + 1;
System.out.println(value);

Output:

text
-2147483648

The value wraps after reaching the maximum. This is important because Java integer overflow does not produce an error or exception. When working with large values, you should understand the range of the selected type.

Literal Type Also Matters

Consider this calculation:

java
long total = 2_000_000_000 + 1_000_000_000;

Even though the result variable is long, the addition is first performed using int arithmetic. The result overflows before it is stored, so total becomes -1294967296. Making the literals long is safer, because now the calculation uses the long range:

java
long total = 2_000_000_000L + 1_000_000_000L;

Floating-Point Types

Java provides two primitive types for decimal or fractional values: float and double.

float

float is a 32-bit floating-point type. Its approximate precision is generally 6–7 significant decimal digits. Decimal literals are double by default, so a float literal needs an F suffix, as in float temperature = 36.5F; (without F, see Common Mistakes).

double

double is a 64-bit floating-point type. It provides more precision than float and is more commonly used for general decimal calculations in Java. Decimal literals are double by default, so no suffix is required:

java
double averageMark = 85.75;
double temperature = 36.5;
double distance = 12.75;

float or double?

TypeSizeApproximate Precision
float32 bits6–7 significant digits
double64 bits15–16 significant digits

General rule:

Use double for general decimal calculations.

float is useful when 32-bit floating-point is specifically required or memory usage is important.

Floating-Point Precision

float and double represent decimal values using binary floating-point format, and not every decimal number can be represented exactly in binary:

java
double result = 0.1 + 0.2;
System.out.println(result);

Output:

text
0.30000000000000004

This is not a Java bug. It is a limitation of floating-point representation.

Why Should We Avoid double for Money?

For exact values such as money, floating-point approximation can create problems, so double amount = 0.1 + 0.2; is risky. In this course, we will represent monetary values exactly using integer minor units:

java
long priceInPaisa = 499_050L;

If 100 paisa = 1 BDT, then 499,050 paisa = BDT 4,990.50. Similarly, for a cent-based currency:

java
long priceCents = 4_990L;

It is important to make the monetary unit clear in the variable name.

char

char represents a single UTF-16 code unit. The literal is written inside single quotes:

java
char grade = 'A';
char symbol = '#';
char banglaLetter = 'ক';

The single character 'A' and the String "Java" are not the same.

char and String

java
char firstLetter = 'J';
String language = "Java";

A char stores one code unit. A String represents a sequence of text and is not a primitive type. This distinction will become clearer in the String lesson (1.11).

Invalid char

char language = 'Java'; does not compile, because single quotes hold exactly one character. Use char firstLetter = 'J'; for one character, or String language = "Java"; for text.

boolean

boolean represents a logical state. Its possible values are true and false:

java
boolean isAvailable = true;
boolean paymentCompleted = false;
boolean hasPermission = true;

Unlike some other languages, Java does not treat 1 as true or 0 as false: boolean isActive = 1; does not compile, and neither does boolean isActive = "true";, because "true" is a String. Only true and false themselves are boolean values. As lessons 1.08 and 1.09 explained, boolean names should read as a condition, such as isActive, hasPermission or canEnroll.

Primitive and Reference Types

A primitive type, such as int, double, char or boolean, represents a basic value. String is not a primitive type: in String studentName = "Sakib";, String is a reference type, and the variable refers to an object. For now, remember that primitives hold basic values and reference types work with objects.

We will understand reference types in more detail when we learn object-oriented programming.

Choosing the Correct Data Type

When choosing a data type, consider the nature of the value and its possible range. Even though a student's age would fit inside a byte, int is generally more practical for normal application code. For exact money, use cents or another minor unit depending on the currency.

Primitive Type Selection Guide

RequirementSuggested Type
General whole numberint
Very large whole numberlong
General decimal calculationdouble
32-bit approximate decimal requiredfloat
Single UTF-16 code unitchar
True/false stateboolean
Exact monetary valuelong minor units
Raw 8-bit binary valuebyte

Complete Example

java
public class Main {

    public static void main(String[] args) {
        String studentName = "Sakib";
        int mathematicsMark = 80;
        int englishMark = 90;
        int scienceMark = 85;

        int totalMarks = mathematicsMark + englishMark + scienceMark;
        double averageMark = totalMarks / 3.0;
        char grade = 'A';
        boolean isPassed = true;

        System.out.println("Student: " + studentName);
        System.out.println("Total: " + totalMarks);
        System.out.println("Average: " + averageMark);
        System.out.println("Grade: " + grade);
        System.out.println("Passed: " + isPassed);
    }
}

Output:

text
Student: Sakib
Total: 255
Average: 85.0
Grade: A
Passed: true

In this program, the marks and total are int, the average is double (dividing by 3.0 keeps the decimal part), the grade is char and the passed status is boolean. The student name is a String, which is not primitive.

Predict the Result

Decide what each program prints, or whether it compiles, before reading the answer.

Question 1

java
public class Main {

    public static void main(String[] args) {
        int maximum = 2_147_483_647;
        int nextInt = maximum + 1;
        long nextLong = maximum + 1L;

        System.out.println(nextInt);
        System.out.println(nextLong);
    }
}

Answer

text
-2147483648
2147483648

maximum + 1 is int arithmetic, so it wraps around to the smallest int. In maximum + 1L the L makes the addition use the long range, so the result is correct.

Question 2

java
public class Main {

    public static void main(String[] args) {
        long millisecondsPerYear = 365 * 24 * 60 * 60 * 1000;

        System.out.println(millisecondsPerYear);
    }
}

Answer

text
1471228928

The correct value is 31536000000, but every literal is an int, so the multiplication overflows before the result is stored in the long variable. Writing 365L * 24 * 60 * 60 * 1000 gives the right answer.

Question 3

<!-- error -->
java
public class Main {

    public static void main(String[] args) {
        long viewCount = 3_000_000_000;

        System.out.println(viewCount);
    }
}

Answer

It does not compile: integer number too large. A whole-number literal without L is an int, and 3_000_000_000 is outside the int range, even though the variable is a long. 3_000_000_000L fixes it.

Question 4

java
public class Main {

    public static void main(String[] args) {
        char grade = 'A';

        System.out.println(grade);
        System.out.println(grade + 1);
    }
}

Answer

text
A
66

A char is stored as a number, and 'A' has the code 65. On its own it prints as a character, but grade + 1 is arithmetic, so the result is the int 66 (lesson 1.13 explains this conversion).

Common Mistakes

Value Outside the byte Range

byte value = 200; does not compile: incompatible types: possible lossy conversion from int to byte. "Lossy conversion" means the value would not survive the trip into the smaller type. Use int value = 200; unless you really need a byte.

Missing F in a float Literal

float temperature = 36.5; fails with a similar message, possible lossy conversion from double to float, because 36.5 is a double literal. Write 36.5F. (A missing L on a large long literal is Predict the Result Question 3.)

Integer Division

double result = 5 / 2; gives 2.0, because 5 / 2 performs integer division first. Correct, giving 2.5:

java
double result = 5.0 / 2;

Wrong Quotes for char

char grade = "A"; gives incompatible types: String cannot be converted to char: double quotes always make a String, even around one letter. Write char grade = 'A';.

Practice Exercise 1: Select the Type

Solutions: lesson 1.23.

Choose a suitable type for each value:

  1. Student age
  2. Course lesson count
  3. 5 billion users
  4. Average mark
  5. Grade A
  6. Whether a user is active
  7. File size in bytes
  8. Temperature
  9. Maximum login attempts
  10. A Bangla letter

Practice Exercise 2: Literal Type

Write the usual type of each literal:

java
100
100L
10.5
10.5F
'A'
true

Practice Exercise 3: Find the Invalid Declarations

Find and correct the invalid declarations:

java
byte age = 25;
byte value = 200;
int lessonCount = 120;
long population = 8_000_000_000L;
float temperature = 36.5F;
double average = 81.67;
char grade = "A";
boolean available = true;
boolean active = 1;

Practice Exercise 4: Integer Division

Predict the output:

java
int firstResult = 5 / 2;
double secondResult = 5 / 2;
double thirdResult = 5.0 / 2;
System.out.println(firstResult);
System.out.println(secondResult);
System.out.println(thirdResult);

Practice Exercise 5: Prevent Overflow

Correct the following code so that the result is 4000000000:

java
long total = 2_000_000_000 + 2_000_000_000;

Practice Exercise 6: Represent Money

The course price is BDT 4,990.50. Assuming 1 BDT = 100 paisa, answer:

  1. What is the value in paisa?
  2. Which primitive type would you use?
  3. What would be a meaningful variable name?

Practice Exercise 7: Student Result

Write a program containing the following, using your own values:

  • Student name → String
  • Mathematics mark → int
  • English mark → int
  • Science mark → int
  • Total → int
  • Average → double
  • Grade → char
  • Passed → boolean

Knowledge Check

Question 1

How many primitive data types are there in Java?

Question 2

What are the eight primitive types?

Question 3

What are the integer primitive types?

Question 4

Which type is generally used for ordinary whole numbers?

Question 5

Which type is used for whole numbers larger than the int range?

Question 6

What suffix is used for a long literal?

Question 7

What type is a decimal literal by default?

Question 8

What suffix is used for a float literal?

Question 9

Which is more common for general decimal calculations: float or double?

Question 10

What is the result of 5 / 2?

Question 11

What is integer overflow?

Question 12

Why might 0.1 + 0.2 not be exactly 0.3?

Question 13

What will we use in this course to represent exact monetary values?

Question 14

Which quotation marks does char use?

Question 15

What are the possible values of boolean?

Question 16

Is String a primitive type?

Knowledge Check Answers

Answer 1

Java has eight primitive data types.

Answer 2

byte, short, int, long, float, double, char and boolean.

Answer 3

byte, short, int and long.

Answer 4

int is generally used for ordinary whole numbers.

Answer 5

long is used.

Answer 6

L

Answer 7

A decimal literal is double by default.

Answer 8

F

Answer 9

double is more common for general decimal calculations.

Answer 10

2, because this is integer division.

Answer 11

Integer overflow occurs when a numeric result exceeds the maximum range of its integer type and wraps around.

Answer 12

Because double uses binary floating-point representation, and not every decimal value can be represented exactly.

Answer 13

We will use integer minor units, generally stored in a long, for exact monetary values.

Answer 14

Single quotes, as in 'A'.

Answer 15

true and false.

Answer 16

No. String is a reference type.

Lesson Summary

  • Java has eight primitive data types: byte, short, int, long, float, double, char and boolean.
  • Use int for general whole numbers and long when the int range is not enough; byte and short need a specific reason.
  • A long literal needs an L suffix, a float literal needs an F suffix, and a decimal literal is double by default.
  • Dividing two integers discards the fractional part, and integer overflow wraps around without an error.
  • float and double are approximate, so in this course exact monetary values are stored as integer minor units in a long.
  • char stores a single UTF-16 code unit in single quotes, boolean stores only true or false, and String is a reference type, not a primitive.

Mõtle enne

Tulekul

Kontrollküsimused, mille puhul valid vastuse enne, kui õppetund selle näitab.