Data Types
Last updated
Was this helpful?
Last updated
Was this helpful?
In Java, data types are used to define the type of data a variable can hold. Data types determine the size and format of data that can be stored in a variable, as well as the operations that can be performed on that data. Java has two categories of data types: primitive data types and reference data types. In this documentation, we will explore both categories in detail.
Primitive data types are the fundamental data types provided by Java, and they are divided into four categories: integral, floating-point, character, and boolean. Let's take a closer look at each of these types.
byte
Size: 8 bits (1 byte)
Range: -128 to 127
Example:
short
Size: 16 bits (2 bytes)
Range: -32,768 to 32,767
Example:
int
Size: 32 bits (4 bytes)
Range: -2^31 to 2^31-1
Example:
long
Size: 64 bits (8 bytes)
Range: -2^63 to 2^63-1
Example:
float
Size: 32 bits (4 bytes)
Example:
double
Size: 64 bits (8 bytes)
Example:
char
Size: 16 bits (2 bytes)
Represents a single Unicode character.
Example:
boolean
Size: JVM-dependent (commonly 1 bit)
Represents true or false.
Example:
Reference data types are used to refer to objects. These data types do not store the actual data but store references to the memory location where the data is stored. Common reference data types include:
String
Used to store a sequence of characters.
Example:
Arrays
Used to store multiple values of the same data type.
Example:
Classes
User-defined data types that can have attributes and methods.
Example:
Interfaces
Defines a contract for implementing classes.
Example:
Enums
A special data type for a predefined set of constants.
Example:
Understanding Java data types is essential for writing effective and efficient Java programs. You should choose the appropriate data type for your variables based on the nature of the data you intend to store. Keep in mind the size and range of the data types to prevent overflow or loss of precision.