Primitive Types
Java has eight primitive types for simple values.
A primitive variable holds its value directly. Pick the type that matches the data:
| Type | What it stores | Range |
|---|---|---|
byte | Small whole numbers | -128 to 127 |
short | Small whole numbers | -32,768 to 32,767 |
int | Everyday whole numbers | -2,147,483,648 to 2,147,483,647 |
long | Very large whole numbers | about ±9.2 quintillion |
float | Decimal numbers with less precision | about 7 digits |
double | Everyday decimal numbers | about 15 digits |
char | One UTF-16 code unit, such as 'A' | 0 to 65,535 |
boolean | Either true or false | two values |
You will use int, double, boolean, and char most often in this course. String is not in the table because it is a class, not a primitive type.
Store student details
public class Main {
public static void main(String[] args) {
int age = 16;
double average = 87.5;
boolean passed = true;
char grade = 'A';
System.out.println("Age: " + age);
System.out.println("Average: " + average);
System.out.println("Passed: " + passed);
System.out.println("Grade: " + grade);
}
}
Output:
Age: 16
Average: 87.5
Passed: true
Grade: A
Each declaration matches the kind of value it stores. Java converts a primitive to text when it is joined to a label for printing.
double is suitable for measurements but not exact decimal money calculations. Production money code commonly stores an integer number of cents.
Choose the primitive types for a product's details.