Java data types
- Data types specify the type of data that can be stored inside Java Variables.
- Java is a statically-typed language. This means that all variables must be declared before they can be used.
Java has 9 built-in data types:
Primitive Data Types
There are 8 different primitive data types:
Tipo | Operatori | Esempio | Intervallo | Space |
---|---|---|---|---|
byte | + - * / % | 27 + 1 | -128…127 | 1 byte |
short | + - * / % | 27 + 1 | -32768…32767 | 2 byte |
int | + - * / % | 27 + 1 | -2147483648…2147483647 | 4 byte |
long | + - * / % | 27 + 1 | -1e9…1e9 | 8 byte |
float | + - * / % | 3.14 * 5.01e23 | 7 cifre decimali significative | 4 byte |
double | + - * / % | 3.14 * 5.01e23 | 15 cifre decimali significative | 8 byte |
boolean | && || ! | true || false | true, false | 1 byte |
char | + - | ‘a’ | Tutti i caratteri codificati con unicode | 2 byte |
String | + - | “Hello” + “World” | ||
oss: Strings are not primitive data types
boolean type
- The
boolean
data type has two possible values, eithertrue
orfalse
. - Default value:
false
byte type
- The
byte
data type can have values from -128 to 127 (8-bit signed two’s complement integer). - If it’s certain that the value of a variable will be within -128 to 127, then it is used instead of int to save memory.
- Default value: 0
short type
- The
short
data type in Java can have values from -32768 to 32767 (16-bit signed two’s complement integer). - If it’s certain that the value of a variable will be within -32768 and 32767, then it is used instead of other integer data types (
int
,long
). - Default value: 0
int type
- The
int
data type can have values from to (32-bit signed two’s complement integer). - Default value: 0
long type
- The long data type can have values from to (64-bit signed two’s complement integer).
- Default value: 0
Warning
You must write the literal with the f ant the and
Notice, the use of L
at the end of -42332200000
. This represents that it’s an integer of the long
type.
double type
- The
double
data type is a double-precision 64-bit floating point. - It should never be used for precise values such as currency.
- Default value: 0.0 (0.0d)
float type
- The float data type is a single-precision 32-bit floating point.
- It should never be used for precise values such as currency.
- Default value: 0.0 (0.0f)
Warning
You must write the literal with the f ant the and
Notice that we have used -42.3f instead of -42.3in the above program. It’s because -42.3 is a double literal.
To tell the compiler to treat -42.3 as float rather than double, you need to use f or F.
char type
- It’s a 16-bit Unicode character.
- The minimum value of the char data type is
'\u0000'
(0) and the maximum value of the is'\uffff'
. - Default value:
'\u0000'
String type
Java also provides support for character strings via java.lang.String class
. Strings in Java are not primitive types. Instead, they are objects.
Here, myString
is an object of the String
class. To learn more, visit Java Strings.