Java is a strongly typed language. That is a fancy way of saying every variable
has a specific type, and once you declare it, that type does not change. You cannot
put a decimal into an int variable and expect Java to be happy about it.
There are two categories of types in Java: primitive types and reference types. We will start with primitives โ the basic building blocks.
Primitive Data Types
Java has eight primitive types. Here are the ones you will use most often:
| Type | Size | Range | Example |
|---|---|---|---|
byte |
8 bits | -128 to 127 | byte b = 100; |
short |
16 bits | -32,768 to 32,767 | short s = 5000; |
int |
32 bits | -2^31 to 2^31-1 | int i = 100000; |
long |
64 bits | -2^63 to 2^63-1 | long l = 100L; |
float |
32 bits | ยฑ3.4e-38 to ยฑ3.4e38 | float f = 3.14f; |
double |
64 bits | ยฑ1.7e-308 to ยฑ1.7e308 | double d = 3.14; |
char |
16 bits | 0 to 65,535 (Unicode) | char c = 'A'; |
boolean |
1 bit | true or false | boolean flag = true; |
In practice, you will use int for whole numbers, double for
decimals, char for single characters, and boolean for
true/false values most of the time. The others have their uses, but you can get
very far with just those four.
Type Ranges in Action
Let us see what happens when you use different types. Notice how Java handles the math differently for integers versus decimals.
public class Main {
public static void main(String[] args) {
int apples = 10;
int people = 3;
double pricePerApple = 1.25;
System.out.println(apples / people);
System.out.println(pricePerApple * apples);
}
}
Notice that 10 / 3 gives you 3, not 3.33.
That is because integer division in Java drops the decimal part. If you want the
decimal, you need to use a double.
char and boolean
Two more primitives you will run into all the time:
public class Main {
public static void main(String[] args) {
char grade = 'A';
boolean passed = true;
System.out.println("Grade: " + grade);
System.out.println("Passed: " + passed);
}
}
char holds a single character and uses single quotes. boolean
holds either true or false โ no maybe, no sometimes, no
I will get back to you. Just true or false.