Datatypes

As the name suggests, data-type specifies the type of the data present in the variable. Variables must be declared with a data-type.

There are two groups of Data types in Java.

i. Primitive data types

Primitive data types specifies the type and size of the data present in variables and they don't have additional methods.

Data typeDescriptionRangeSize
intused to store whole numbers-2,147,483,648 to 2,147,483,6474 bytes
shortused to store whole numbers-32,768 to 32,7672 bytes
longused to store whole numbers-9,223,372,036,854,775,808 to 9,223,372,036,854,775,8078 bytes
byteused to store whole numbers-128 to 1271 byte
floatused to store fractional numbers6 to 7 decimal digits4 bytes
doubleused to store fractional numbers15 decimal digits8 bytes
booleancan either store true or falseeither true or false1 bit
charused to store a single characterone character2 bytes

Examples

1. Integer data type

int is used to store whole numbers from -2147483648 to 2147483647.

int x = 99999; 
System.out.println(x);

2. Short data type

short is used to store whole numbers from -32768 to 32767

short x = 999; 
System.out.println(x);

3. Long data type

Long is used when int is not enough to hold the data and can store whole numbers from -9223372036854775808 to 9223372036854775807. You should put L at the end of the value.

long x = 99999999999L;
System.out.println(x);

4. Byte data type

Byte can store whole numbers from -128 to 127. This data type is used to save memory and is used when the value is with in -128 to 127.

byte x = 99;
System.out.println(x);

5. Double data type

Double is used store fractional numbers in the range 1.7e−308 to 1.7e+308. You should put d at the end of the value.

double x = 99.99d;
System.out.println(x);

6. Boolean data type

Boolean data type is used only when the value is either true or false.

boolean isAvailable = true;
System.out.println(isAvailable);

7. Char data type

char data type is used to store single character. Single quotes are used to represent characters.

char division = 'A';
System.out.println(division);

ii. Non-Primitive data types

Non-primitive data types specifies the complex data values and it can have additional methods. Usually non-primitive data types are created by the developer (except for String).

For example, strings, arrays and classes can be referred as Non-primitive data types and are discussed in later sections.