Primitive data types in Java
Java supports eight primitive data types:
int
int
, byte
byte
, short
short
, long
long
, double
double
, float
float
, boolean
boolean
, and char
char
.
int age = 24; // integer
byte workingDaysPerMonth = 22; // integer used for very short numbers
short compensation = 7476; // integer used for short numbers
long yearsOld = 300000; // integer used for large numbers
double hourlyRate = 42.48; // floating-point
float pi = 3.14f; // floating-point used for precise numbers
boolean isLegalAge = true; // true or false
char initialLetter = 'B'; // single quote with a single Unicode character
int age = 24; // integer
byte workingDaysPerMonth = 22; // integer used for very short numbers
short compensation = 7476; // integer used for short numbers
long yearsOld = 300000; // integer used for large numbers
double hourlyRate = 42.48; // floating-point
float pi = 3.14f; // floating-point used for precise numbers
boolean isLegalAge = true; // true or false
char initialLetter = 'B'; // single quote with a single Unicode character
Type casting
(int)
(int)
converts to int
int
.
int hourlyRate = (int) 42.48;
int hourlyRate = (int) 42.48;
(float)
(float)
converts to float
float
.
float hourlyRate = (float) 42.48;
float hourlyRate = (float) 42.48;
Any decimal number is interpreted as a double
double
.
float num = 3.14; // compile error because can not implicitly convert from double to float
float num = 3.14; // compile error because can not implicitly convert from double to float
Add the letter f
f
at the end or (float)
(float)
at the beginning:
float num = 3.14f;
float num = 3.14f;
The letter f
f
tells it is a floating-point number.