Skip to main content
Advertisement

2.4 Primitive Types

Java provides 8 primitive data types, which can be broadly divided into 4 categories: logical, character, integer, and floating-point types. In this section, we will look in detail at the characteristics and uses of each type.

1. Logical Type: boolean

The logical type can hold only two values: true and false. Its default value is false. Boolean variables are used to express logical states such as answers (yes/no) or switches (on/off). It occupies 1 byte of space to store data (as per memory allocation in Java specifications).

boolean isPowerOn = true;
boolean hasPermission = false;

2. Character Type: char

The character type is used to store exactly one character, which must be enclosed in single quotes ('). It is distinct from strings, and internally, the Unicode integer value corresponding to the character is stored. A character in Java occupies 2 bytes.

char ch1 = 'A';       // Character 'A'
char ch2 = 65; // Decimal 65 is an uppercase A
char ch3 = '\u0041'; // Unicode hexadecimal format

System.out.println(ch1); // A
System.out.println(ch2); // A

3. Integer Types: byte, short, int, long

Integer types store whole numbers, and you must choose one of the 4 types based on the size range of the value.

Data TypeSize (bytes)Range
byte1-128 ~ 127
short2-32,768 ~ 32,767
int4Approx -2.1B ~ 2.1B (Default integer type)
long8Very large integers (Approx -9E18 ~ 9E18)

Usage Examples

byte b = 127; 
short s = 32767;
int i = 2147483647;
long l = 10000000000L; // long literals require the suffix 'L'

The most frequently used type is int, as it is set as the default in terms of calculation speed and efficiency.

4. Floating-Point Types: float, double

Floating-point types are used to represent real numbers containing decimal points.

Data TypeSize (bytes)Features
float4About 7 digits of precision
double8About 15 digits of precision (Default real number type)

Precision and Rules of Use

Real number operations can result in errors, so the double type, which guarantees high precision, is used by default. When using the float type, you must append the suffix f or F after the number.

float pi1 = 3.14f;    // float literal requires the suffix 'f'
double pi2 = 3.14; // Without a suffix, it is considered a double
double pi3 = 3.14d; // Explicit representation of a double

In Java, real numbers follow the floating-point scheme, which divides the number into a mantissa and an exponent part, allowing representations of an even broader range of values.

Advertisement