Matheus Almeida's iconMatheusAlmeida

Primitive data types in Java

Java supports eight primitive data types:

intint, bytebyte, shortshort, longlong, doubledouble, floatfloat, booleanboolean, and charchar.

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 intint.

int hourlyRate = (int) 42.48;
int hourlyRate = (int) 42.48;

(float)(float) converts to floatfloat.

float hourlyRate = (float) 42.48;
float hourlyRate = (float) 42.48;

Any decimal number is interpreted as a doubledouble.

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 ff at the end or (float)(float) at the beginning:

float num =  3.14f;
float num =  3.14f;

The letter ff tells it is a floating-point number.