Lesson 5
Datatypes
A beginner-friendly guide to Java data types, memory size and value ranges.
Java Track
Save progress as you learn.
61 lessons
Lesson content
Java data types tell the compiler what kind of value a variable can store and how much memory it needs.
Data types in Java
Data types are divided into two groups: primitive data types and non-primitive data types.
- Primitive data types include byte, short, int, long, float, double, boolean and char.
- Non-primitive data types include String, Arrays and Classes.
Primitive data types and sizes
- byte - 1 byte
- short - 2 bytes
- int - 4 bytes
- long - 8 bytes
- float - 4 bytes
- double - 8 bytes
- boolean - 1 bit
- char - 2 bytes
Byte
The byte data type can store whole numbers from -128 to 127.
byte myNum = 100;
System.out.println(myNum);Short
The short data type can store whole numbers from -32768 to 32767.
short myNum = 5000;
System.out.println(myNum);Integer
The int data type can store whole numbers from -2147483648 to 2147483647. It can store whole numbers.
Example: int a = 10;
Long
The long data type can store whole numbers from -9223372036854775808 to 9223372036854775807.
This is used when int is not large enough to store the value. Note that you should end the value with an L.
long myNum = 15000000000L;
System.out.println(myNum);Floating Point Types
You should use a floating point type whenever you need a number with a decimal, such as 9.99 or 3.14515.
The float and double data types can store fractional numbers. Note that you should end the value with an f for floats and d for doubles.
Float Example
float myNum = 5.75f;
System.out.println(myNum);Double Example
double myNum = 19.99d;
System.out.println(myNum);Boolean
Java has a boolean data type, which can only take the values true or false.
boolean isJavaFun = true;
boolean isFishTasty = false;
System.out.println(isJavaFun); // Outputs true
System.out.println(isFishTasty); // Outputs falseCharacters
The char data type is used to store a single character. The character must be surrounded by single quotes, like 'A' or 'c'.
char myGrade = 'B';
System.out.println(myGrade);Non-Primitive Data Types
Non-primitive data types are called reference types because they refer to objects.
Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc.